PythonMastery
Python programs · Useful programs · intermediate

Sort a list by frequency in Python

Sort a list so the most common values come first, with ties in order, using collections.Counter and a sort key. Count once, not inside the key.

This program sorts a list so that the values that appear most often come first. When two values appear the same number of times, the smaller value comes first.

The program

python
from collections import Counter

nums = [3, 1, 2, 2, 4, 1, 2, 3, 5]

counts = Counter(nums)
result = sorted(nums, key=lambda n: (-counts[n], n))

print(counts)
print(result)
output
Counter({2: 3, 3: 2, 1: 2, 4: 1, 5: 1})
[2, 2, 2, 1, 1, 3, 3, 4, 5]

How it works

The counting happens once, before the sort. Writing Counter(nums)[n] inside the key would count the whole list again for every item, which is very slow for long lists.

Just the most common values

If you only need each value once, with its count, most_common() gives that list directly:

python
from collections import Counter

words = "the cat and the dog and the bird".split()
for word, count in Counter(words).most_common(3):
    print(word, count)
output
the 3
and 2
cat 1

When counts are equal, most_common() keeps the order in which the values first appeared.

Learn the idea: collections: The Stdlib's Hidden Power, Lambda & Functional Programming