12
\$\begingroup\$

This is a tips question for golfing in Python, which is on topic for main.

I'm looking for the shortest way to get all of the most common elements of a list in Python, in the shortest way possible. Here's what I've tried, assuming the list is in a variable called l:

from statistics import*
mode(l)

This throws an error if there are multiple modes.

max(l,key=l.count)

This only returns 1 item, I need to get all the elements of greatest count.

from collections import*
Counter(l).most_common()

This returns a list of tuples of (element, count), sorted by count. From this I could pull all the elements whose corresponding count is equal to the first, but I don't see a way to golf this much better than:

from collections import*
c=Counter(l).most_common()
[s for s,i in c if i==c[0][1]]

I am sure there is a shorter way!

Also, if it can be done without variable assignment or multiple uses of l, I can keep the rest of the code as a lambda expression to save more bytes.

Edit: Per @Uriel's suggestion, we can do:

{s for s in l if l.count(s)==l.count(max(l,key=l.count))}

And I can alias list.count for a few bytes:

c=l.count;{s for s in l if c(s)==c(max(l,key=c))}

@Uriel pointed out that we can get a couple more bytes with map:

c=l.count;{s for s in l if c(s)==max(map(c,l))}
\$\endgroup\$
1
  • \$\begingroup\$ Related, but doesn't do what I need \$\endgroup\$ Jul 18, 2017 at 22:36

1 Answer 1

5
\$\begingroup\$

How about this one?

c=l.count;{x for x in l if c(x)==max(map(c,l))}

Enclose in [*...] to get a list.

\$\endgroup\$
3
  • \$\begingroup\$ Oh right, I do need a unique list or set, thanks \$\endgroup\$ Jul 18, 2017 at 22:46
  • \$\begingroup\$ @musicman523 why did you update with l.count(max(l,key=l.count))? max(map(l.count,l)) is shorter \$\endgroup\$
    – Uriel
    Jul 18, 2017 at 22:50
  • \$\begingroup\$ Ahhhh I didn't think of that one, thank you! \$\endgroup\$ Jul 18, 2017 at 22:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.