# Most common elements of a list in Python

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]


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))}

• Related, but doesn't do what I need Jul 18, 2017 at 22:36

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

Enclose in [*...] to get a list.
• @musicman523 why did you update with l.count(max(l,key=l.count))? max(map(l.count,l)) is shorter Jul 18, 2017 at 22:50