Most common elements of a list in Python

13

1

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

musicman523

Posted 2017-07-18T22:33:45.837

Reputation: 4 472

Related, but doesn't do what I need – musicman523 – 2017-07-18T22:36:54.013

Answers

5

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.

Uriel

Posted 2017-07-18T22:33:45.837

Reputation: 11 708

Oh right, I do need a unique list or set, thanks – musicman523 – 2017-07-18T22:46:49.647

@musicman523 why did you update with l.count(max(l,key=l.count))? max(map(l.count,l)) is shorter – Uriel – 2017-07-18T22:50:25.097

Ahhhh I didn't think of that one, thank you! – musicman523 – 2017-07-18T22:55:35.417