man python/counter-and-heapq
Counter, most_common and heapq: top-k in the standard library
A typical collections.Counter job: count IDs, then ask for the three most common and the three least common. Two spellings of “least common” gave different answers when several IDs shared the lowest count:
counts.most_common()[-3:] # keeps the LAST tied IDs seen
heapq.nsmallest(3, counts, key=counts.get) # keeps the FIRST tied IDs seen
This article follows both calls into the CPython 3.15.2 source to see why. Along the way it measures how many comparisons each approach makes and how long it takes.
Notation: k is the number of distinct keys in the Counter, n is how many results you ask for (3 here). The comments in heapq.py use the letters the other way round, so I translate when quoting them.
What a Counter is
Counter is a plain Python class that subclasses dict (class Counter(dict):, Lib/collections/__init__.py line 551). Keys are the things counted and values are their counts. Two small overrides make it feel like a multiset:
__missing__returns0(L619-622), soc["nope"]gives0. It does not insert the key.fromkeysraisesNotImplementedError(L666-675), becauseCounter.fromkeys("aaab", v=2)has no clear meaning.
How Counter(iterable) counts
Counter.__init__ calls super().__init__() and then self.update(iterable, **kwds). update (L677-709) has two branches. If the argument is a Mapping, it adds the counts, with a fast path through dict.update when the Counter is still empty. Anything else goes to _count_elements(self, iterable) (L707).
The module defines _count_elements in Python first (L540-543):
def _count_elements(mapping, iterable):
'Tally elements from the iterable.'
mapping_get = mapping.get
for elem in iterable:
mapping[elem] = mapping_get(elem, 0) + 1
and then replaces it with a C version when one exists (L546-549):
try: # Load C helper function if available
from _collections import _count_elements
except ImportError:
pass
The C version lives in Modules/_collectionsmodule.c (L2545 onward). Before looping, it looks up get and __setitem__ on the mapping’s type and compares them with dict’s own (L2563-2574). The fast path runs only if neither is overridden and PyDict_Check(mapping) is true. The comment in that loop lists what it saves: it hashes each key once and reuses the hash for both the lookup and the store, it avoids argument tuples and bound-method calls, and it stores a shared 1 object for new keys instead of computing 0 + 1.
If a subclass overrides either method, the C function takes a generic loop (L2618 onward). That loop calls the bound get and then PyObject_SetItem, so your override runs for every element.
Here is the cost of each route on 1,000,000 strings with 1,000 distinct values. LoudCounter is a Counter subclass whose __setitem__ just calls super().__setitem__.
$ python3.15 -I counting.py
3.15.2 | 1,000,000 items, 1,000 distinct
Counter(data) 30.1 ms
py_count_elements(Counter(), data) 86.0 ms
LoudCounter(data) 150.7 ms
py_count_elements(LoudCounter(), data) 156.3 ms
On Python 3.15.2 on an Apple M2 Pro, the C fast path is about 2.9 times faster than the pure Python fallback. Once a Python-level __setitem__ runs per element, that cost dominates, and the C generic loop and the Python fallback land within 4% of each other.
most_common with and without n
The whole method is four lines (L628-640, docstring omitted):
# Emulate Bag.sortedByCount from Smalltalk
if n is None:
return sorted(self.items(), key=_itemgetter(1), reverse=True)
return _nlargest(n, self.items(), key=_itemgetter(1))
Without n it sorts all k items: O(k log k) comparisons and a new list of k tuples. With n it hands the work to heapq.nlargest. Since self.items() has a length, nlargest takes one of its shortcuts first (below): n == 1 becomes max(), and n >= k becomes the same sorted(..., reverse=True) call. The heap only runs when 1 < n < k.
Inside heapq.nsmallest and nlargest
Both functions are pure Python in Lib/heapq.py (nsmallest L477-535, nlargest L537-594). They make one pass over the input and keep only n items. Shortcuts come first:
n == 1: returnmin(it, default=sentinel, key=key)wrapped in a list (L483-487).- If
len(iterable)works andn >= size, returnsorted(iterable, key=key)(L489-496).
Then the main loop. With a key, the general case (L519-535) is:
it = iter(iterable)
result = [(key(elem), i, elem) for i, elem in zip(range(n), it)]
if not result:
return result
heapify_max(result)
top = result[0][0]
order = n
_heapreplace = heapreplace_max
for elem in it:
k = key(elem)
if k < top:
_heapreplace(result, (k, order, elem))
top = result[0][0]
order += 1
result.sort()
return [elem for (k, order, elem) in result]
The heap is a max-heap of the n best candidates so far. Its root is the worst of them. Each new element costs one comparison against top, a bare key with no tuple. Only a winner enters the heap. The i/order index sits between the key and the element, so equal keys never compare the elements themselves, and an earlier element always sorts before a later one with the same key. Without a key, the decoration is (elem, i) (L498-517). nlargest mirrors all of this with a min-heap, top < k, and an index that counts down from 0 (range(0, -n, -1), then order -= 1) so that earlier elements still win ties after result.sort(reverse=True).
The split between Python and C is at the bottom of the file (L596-599):
try:
from _heapq import *
except ImportError:
pass
That import replaces heapify, heappush, heappop, heapreplace, heappushpop and their _max variants with C functions from Modules/_heapqmodule.c (method table L638-651). nsmallest looks up heapify_max and heapreplace_max as module globals at call time, so the sifting runs in C. The loop, the key calls and the k < top test run as Python bytecode.
The notes above the functions (L411-475) give the cost for random input as roughly k + n * (log2(n) * ln(k/n) + log2(n) + ln(k/n)) comparisons, which is O(k) when n is small. The worst case is input in reverse order, where every element enters the heap: 1.66 * n + log2(n) * (k - n) comparisons, so O(k log n). A full sort is O(k log k).
Why ties come out differently
Since 3.7 a Counter keeps insertion order, so tied IDs sit in the order they first appeared. Python’s sort is stable, and the sorting HOWTO states that reverse=True keeps that stability. So most_common() lists the highest count first, and within each count the first-seen ID first. Slicing [-3:] takes the tail of that list, which holds the last-seen IDs among the lowest counts.
nsmallest goes the other way for two reasons in the code. The test is strict (if k < top, L530), so a later key that only equals the current worst candidate never enters the heap. And inside the heap, equal keys are ordered by the rising order index, so earlier elements stay ahead in the final result.sort().
from collections import Counter
import heapq
ids = ["a", "b", "b", "c", "d", "e", "f", "g", "g"]
counts = Counter(ids)
print(counts)
print("most_common(): ", counts.most_common())
print("most_common()[-3:]: ", counts.most_common()[-3:])
print("nsmallest(3, ...): ", heapq.nsmallest(3, counts, key=counts.get))
print("most_common(3): ", counts.most_common(3))
$ python3.15 ties.py
Counter({'b': 2, 'g': 2, 'a': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 1})
most_common(): [('b', 2), ('g', 2), ('a', 1), ('c', 1), ('d', 1), ('e', 1), ('f', 1)]
most_common()[-3:]: [('d', 1), ('e', 1), ('f', 1)]
nsmallest(3, ...): ['a', 'c', 'd']
most_common(3): [('b', 2), ('g', 2), ('a', 1)]
The same two lists came out on 3.9.6, 3.12.16, 3.13.3, 3.14.6 and 3.15.2. If you want the first-seen least common IDs from a sort, sort ascending: sorted(counts, key=counts.get)[:3] gives ['a', 'c', 'd'] too, because a stable ascending sort keeps first-seen order among ties.
Counting comparisons
To count comparisons, each count is wrapped in a class whose __lt__ and __eq__ increment counters. Counts are random integers below 10⁹ (seed 2026), so ties are rare. The last two rows use counts that fall in insertion order, which is the worst case for nsmallest.
class K:
__slots__ = ("v",)
def __init__(self, v): self.v = v
def __lt__(self, other):
calls["lt"] += 1
return self.v < other.v
def __eq__(self, other):
calls["eq"] += 1
return self.v == other.v
__hash__ = None
$ python3.15 -I compares.py
3.15.2
k | method | __lt__ | __eq__
10 | sorted(c, key=c.get)[:3] | 19 | 0
10 | nsmallest(3, c, key=c.get) | 19 | 12
10 | most_common(3) | 24 | 17
10 | most_common()[-3:] | 25 | 0
1000 | sorted(c, key=c.get)[:3] | 8,650 | 0
1000 | nsmallest(3, c, key=c.get) | 1,031 | 34
1000 | most_common(3) | 1,027 | 30
1000 | most_common()[-3:] | 8,660 | 0
100000 | sorted(c, key=c.get)[:3] | 1,531,806 | 0
100000 | nsmallest(3, c, key=c.get) | 100,063 | 66
100000 | most_common(3) | 100,053 | 56
100000 | most_common()[-3:] | 1,531,727 | 0
desc | sorted(c, key=c.get)[:3] | 99,999 | 0
desc | nsmallest(3, c, key=c.get) | 299,999 | 200,002
On random input the heap versions make k plus a few dozen comparisons, which matches the formula above. The sort makes about 15 per key at k = 100,000. The __eq__ calls come from tuple comparisons inside the heap. tuple_richcompare in Objects/tupleobject.c (L760-771) first scans for the first position where the items differ using ==, then applies < to that position. The bare k < top test in the loop never calls __eq__.
The descending rows show the reverse. Every key beats the current worst candidate, so nsmallest pushes all 100,000 into the heap. The sort needs k − 1 comparisons. Objects/listsort.txt (L214-216) says the sort detects a descending run and reverses it in place, and here the whole input is one such run.
Timings
Same Counters with plain int counts, timeit, best of 7 repeats, on Python 3.15.2 on an Apple M2 Pro:
$ python3.15 -I timing.py
3.15.2 arm64
k | method | best µs/call
10 | sorted(c, key=c.get)[:3] | 0.36
10 | nsmallest(3, c, key=c.get) | 1.02
10 | c.most_common(3) | 1.49
10 | c.most_common()[-3:] | 0.49
1000 | sorted(c, key=c.get)[:3] | 67.13
1000 | nsmallest(3, c, key=c.get) | 30.70
1000 | c.most_common(3) | 30.53
1000 | c.most_common()[-3:] | 68.15
100000 | sorted(c, key=c.get)[:3] | 14075.46
100000 | nsmallest(3, c, key=c.get) | 3263.50
100000 | c.most_common(3) | 2852.81
100000 | c.most_common()[-3:] | 17481.68
desc | sorted(c, key=c.get)[:3] | 2562.72
desc | nsmallest(3, c, key=c.get) | 12419.71
The heap wins by about 2.2 times at k = 1,000 and 4.3 to 6 times at k = 100,000. The time gap is much smaller than the comparison gap (8.4 times fewer at k = 1,000) because the heap’s per-element work runs as Python bytecode, while the sort loops in C.
When to sort instead
- Small inputs. At k = 10 the sort is about 3 times faster. The heap’s setup and Python loop cost more than the comparisons they save.
- Input already in the wrong order. With falling counts,
nsmallestwas nearly 5 times slower thansorted. - Large n. The heapq docs say
sorted()is more efficient for larger n, andnsmallestalready switches tosortedwhenn >= len(iterable). - You need the whole ranking.
most_common()sorts once, and every slice after that is free.
Curious facts
repr(counter)callsself.most_common()(L750-759). Printing a large Counter sorts it.- On 3.15.2,
import collectionsdoes not importheapq. Line 36 readslazy from heapq import nlargest as _nlargest(PEP 810 lazy imports, new in 3.15). In a freshpython3.15 -I,'heapq' in sys.modulesstayedFalseaftermost_common()and becameTrueaftermost_common(1). heapqis no longer min-heap only. Python 3.14 added publicheapify_max,heappush_max,heappop_max,heapreplace_maxandheappushpop_max. The old private names such as_heapify_maxremain as aliases “for backwards compatibility” (L601-606).- Counters got
^in 3.15, the symmetric differencemax(c[x], d[x]) - min(c[x], d[x]).Counter(a=3, b=1) ^ Counter(a=1, b=2)givesCounter({'a': 2, 'b': 1}). - The collections docs suggest
c.most_common()[:-n-1:-1]for the n least common elements. It walks the same sorted list backwards, so on ties it also returns the last-seen IDs.
Version history
| Version | Change | Evidence |
|---|---|---|
| 2.4 | heapq converted to C; nlargest and nsmallest added | What’s New in 2.4 |
| 2.5 | key= added to nsmallest and nlargest | What’s New in 2.5 |
| 2.7 / 3.1 | collections.Counter added | What’s New in 2.7 and 3.1; docs “Added in version 3.1” |
| 3.2 | C _count_elements exists; its fast path requires an exact dict, which a Counter never is | PyDict_CheckExact(mapping) at tag v3.2 |
| 3.3 | Unary +/- and in-place multiset operators | What’s New in 3.3 |
| 3.4 | Fast path accepts subclasses that don’t override get/__setitem__ | check absent at v3.3.0, present at v3.4.0 |
| 3.5 | Hash reused for get and set; nlargest/nsmallest rewritten with fewer tuple comparisons; C nlargest/nsmallest gone from _heapq | v3.5.0 source; Misc/NEWS issue 21424; present at v3.4.0, absent at v3.5.0 |
| 3.7 | Counter keeps insertion order as a dict subclass | collections docs |
| 3.10 | Counter.total(); rich comparisons | collections docs |
| 3.14 | Public max-heap functions in heapq | What’s New in 3.14 |
| 3.15 | Counter.__xor__/__ixor__; lazy import of heapq.nlargest | What’s New in 3.15; v3.15.2 source |
Sources
CPython v3.15.2:
Lib/collections/__init__.pyL36, L540-549, L551, L619-626, L628-640, L666-675, L677-709, L750-759Modules/_collectionsmodule.cL2545-2657, fast-path check L2563-2574, generic loop L2618Lib/heapq.pyL411-475 (algorithm notes), L477-535 (nsmallest), L537-594 (nlargest), L596-606Modules/_heapqmodule.cL638-651Objects/listsort.txtL214-216Objects/tupleobject.cL760-771
Older tags:
- v3.2
Modules/_collectionsmodule.cL1552 - v3.4.0
Modules/_collectionsmodule.cL1792-1803, v3.5.0 L2147 - v3.4.0
Modules/_heapqmodule.cL300, v3.5.0Misc/NEWSL2379
Docs:
- collections: Counter
- heapq
- Sorting techniques: stability
- What’s New in 2.4, 2.5, 2.7, 3.1, 3.3, 3.14, 3.15
grep -rl /lib/python/counter-and-heapq/
ls python/
- draft How a Python dict worksInside CPython 3.15's dict: the index table and entries array, the probe sequence, resizing, deletions, and why counting with a dict is linear.
- draft How Python sorts: runs, galloping and powersortWhat CPython 3.15's list.sort does with your data: natural runs, binary insertion sort, a powersort merge stack, galloping, and type-specialised compares.
- draft Multiplying a list in Python: loops, reduce, operator.mul and math.prodWhat a for loop, functools.reduce with a lambda or operator.mul, and math.prod actually execute in CPython 3.15, how fast each one is, and what changes once the product outgrows a machine word.