Counting Without Boilerplate? Python's collections.Counter
This article explains how Python's collections.Counter counts hashable elements, ranks them with most_common, combines counts as multisets, measures its speed against manual loops, and describes its pitfalls.
Counting occurrences is one of the most frequent tasks in data processing: words in a text, status codes in a log, products in a list of orders. The present article addresses collections.Counter, a subclass of dict that maps each hashable element to the number of times it appears, and that adds the operations a plain dictionary lacks: the most common elements, the total, and arithmetic between counts. Its speed is measured against the manual alternatives, and its rules for zero and negative counts are described, because they explain most of the surprises it produces. Turning an iterable into a table of frequencies in one call, with the arithmetic of multisets already defined, is the secret weapon of collections.Counter.
Counting and Ranking
A Counter is built from any iterable, whose elements become keys, or from a mapping of counts. Reading a missing key returns zero instead of raising KeyError, without inserting the key, which is the behaviour of the method __missing__ described in the article devoted to __missing__. The following example counts letters, ranks them and reads the totals.
from collections import Counter
letters = Counter("abracadabra")
print(letters) # Output: Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})
print(letters.most_common(3)) # Output: [('a', 5), ('b', 2), ('r', 2)]
print(letters.most_common()[:-3:-1]) # Output: [('d', 1), ('c', 1)]
print(letters["z"], "z" in letters) # Output: 0 False
print(letters.total()) # Output: 11
letters.update("aaz")
letters.update({"b": 10})
print(letters["a"], letters["b"], letters["z"]) # Output: 7 12 1
The ranking breaks ties by order of first appearance, which is why b precedes r: since Python 3.7, a Counter preserves insertion order like any dictionary, so the description of it as an unordered collection is outdated. The method update adds counts, also when it receives a mapping, whereas dict.update would replace them. For a limited ranking, most_common(n) relies on heapq.nlargest, as described in the article devoted to heapq; on CPython 3.12, the ten most common of 200,000 keys took about 5.8 milliseconds, against 63 for the complete sorted list. The method total, added in Python 3.10, replaces sum(counter.values()).
Arithmetic Between Counters
Counters behave as multisets, collections in which an element may appear several times. Addition sums the counts, subtraction subtracts them, intersection keeps the minimum of each count and union keeps the maximum. All four operators share one rule: the result excludes elements whose count is zero or negative. The method subtract, in contrast, keeps negative counts, and the unary + removes them afterwards. The following example applies the operators to an inventory and compares counters.
from collections import Counter
stock = Counter(apples=4, pears=2)
sold = Counter(apples=1, pears=5)
print(stock + Counter(apples=1)) # Output: Counter({'apples': 5, 'pears': 2})
print(stock - sold) # Output: Counter({'apples': 3})
print(stock & sold) # Output: Counter({'pears': 2, 'apples': 1})
print(stock | sold) # Output: Counter({'pears': 5, 'apples': 4})
balance = stock.copy()
balance.subtract(sold)
print(balance) # Output: Counter({'apples': 3, 'pears': -3})
print(+balance) # Output: Counter({'apples': 3})
print(sorted(balance.elements())) # Output: ['apples', 'apples', 'apples']
print(Counter(a=1) == Counter(a=1, b=0)) # Output: True
print(Counter("listen") == Counter("silent")) # Output: True
print(Counter(a=1) <= Counter(a=2, b=1)) # Output: True
The operator - lost the information that three pears were missing, whereas subtract preserved it as a negative count, so the choice between them depends on whether a deficit matters. Since Python 3.10, equality treats missing elements as zero, and the comparisons <= and >= test inclusion between multisets, which makes the anagram check a single comparison.
Known Bugs: Pitfalls of Counter
A Counter is a dictionary with conventions of its own, and its pitfalls arise where those conventions differ from what a dictionary or a list would do. Six pitfalls are distinguished, which are the following:
- Strings are iterables of characters.
Counter("hello world")counts letters and spaces; counting words requiresCounter(text.split()). - Operators discard deficits.
+,-,&and|drop zero and negative counts, so a balance computed with-hides what is missing. - Zero counts remain keys. Setting a count to zero, or writing
c[key] += 0, keeps the key, which then appears inlenand in iteration until it is deleted or removed with+c. updateadds instead of replacing. Passing a mapping toupdatesums its values into the existing counts.- Manual loops waste the speed. Incrementing
c[item] += 1in a Python loop is slower than a plain dictionary, because each new key calls__missing__. - No memory saving. A
Counterstores the same keys and values as an equivalent dictionary, so its advantage lies in convenience and in the speed of its constructor, not in memory.
The first, third and fifth pitfalls are reproduced in the following example, which compares the constructor with a manual loop over 200,000 words.
import random
import timeit
from collections import Counter
text = "the cat and the hat"
print(Counter(text).most_common(2)) # Output: [('t', 4), (' ', 4)]
print(Counter(text.split()).most_common(1)) # Output: [('the', 2)]
counts = Counter()
counts["unused"] += 0
print(len(counts), counts) # Output: 1 Counter({'unused': 0})
print(len(+counts)) # Output: 0
random.seed(0)
words = [f"w{random.randrange(4000)}" for _ in range(200_000)]
def manual_loop():
c = Counter()
for w in words:
c[w] += 1
return c
t_ctor = min(timeit.repeat(lambda: Counter(words), number=5, repeat=5))
t_loop = min(timeit.repeat(manual_loop, number=5, repeat=5))
print(t_loop > 1.5 * t_ctor) # Output: True
On CPython 3.12, counting 200,000 words took about 6.6 milliseconds with Counter(words), 9.0 with a loop over a plain dictionary and dict.get, 10.3 with defaultdict(int), and 17.6 with c[w] += 1 on a Counter. The constructor is faster because it delegates the loop to a helper written in C, so the gain over a plain dictionary is about a third, not an order of magnitude, and it disappears when the counter is filled element by element.
Choosing a Counting Tool
Consequently, a Counter suits counts that are built from an iterable and then ranked, compared or combined, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| Frequencies of the elements of an iterable | Counter(iterable) |
| Top or bottom elements by count | most_common(n) or most_common()[:-n-1:-1] |
| Merging counts from several sources | update or the operator + |
| Balances that may become negative | subtract, not the operator - |
| Comparing contents regardless of order | Equality or inclusion between counters |
| Grouping values, not counting them | defaultdict(list) |
| A single count of one value | list.count or sum with a generator |
Conclusion
It is concluded that collections.Counter counts hashable elements in one call, preserves the order of first appearance, ranks them with most_common, and treats counts as multisets whose operators discard zero and negative results. This magic has precise limits: strings are counted by character, zero counts remain as keys, and the speed advantage belongs to the constructor rather than to manual loops. Controlling how objects are rendered by format and f-strings through the method __format__ is the subject of a future article of this series.