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
Counter(nums)counts every value in one pass through the list: 2 appears three times, 1 and 3 twice, 4 and 5 once.- The sort key is a tuple,
(-counts[n], n). Python compares tuples item by item: first the negative count, then the value itself. - The minus sign puts the highest count first, because
sorted()sorts from small to large and -3 is smaller than -2. - The second item breaks ties: 1 and 3 both appear twice, and 1 comes first because it is smaller.
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.