Sort list by frequency

I think this would be a good job for a collections.Counter:

counts = collections.Counter(lst)
new_list = sorted(lst, key=lambda x: -counts[x])

Alternatively, you could write the second line without a lambda:

counts = collections.Counter(lst)
new_list = sorted(lst, key=counts.get, reverse=True)

If you have multiple elements with the same frequency and you care that those remain grouped, we can do that by changing our sort key to include not only the counts, but also the value:

counts = collections.Counter(lst)
new_list = sorted(lst, key=lambda x: (counts[x], x), reverse=True)

Leave a Comment