
collections.Counter looks like a dictionary that counts for you. It is — but it also overloads the math operators, and that’s where most surprises live. Here is what Counter actually does, and the four edges that bite people.
The basics
A Counter is a dict subclass keyed by hashable items, with counts as values. Missing keys return 0 instead of raising:
from collections import Counter
votes = ["yes", "no", "yes", "yes", "no", "abstain"]
tally = Counter(votes)
print(tally) # Counter({'yes': 3, 'no': 2, 'abstain': 1})
print(tally["maybe"]) # 0 -> no KeyError, even for unseen keys
print(tally.most_common(1)) # [('yes', 3)]
So far, so convenient.
The arithmetic operators
Counter implements +, -, &, and | element-wise:
a = Counter("aabbc")
b = Counter("abccc")
print(a + b) # Counter({'c': 4, 'a': 3, 'b': 3}) # sums counts
print(a - b) # Counter({'a': 1}) # subtract, then DROP <= 0
print(b - a) # Counter({'c': 2}) # NOT the mirror image
print(a & b) # Counter({'a': 1, 'b': 1}) # min per key
print(a | b) # Counter({'c': 3, 'a': 2, 'b': 2}) # max per key
Gotcha 1: subtraction silently discards leftovers
a - b removes any key whose count drops to zero or below — the discarded counts are gone, not preserved as negatives. That makes a - b and b - a not complements: each throws away what the other kept.
x = Counter(apples=5, bananas=2)
y = Counter(apples=2, bananas=9)
print(x - y) # Counter({'apples': 3}) # bananas vanished (2 - 9 < 0)
print(y - x) # Counter({'bananas': 7}) # apples vanished (2 - 5 < 0)
If you want “how much x exceeds y” use x - y and accept that underflowing keys disappear. Don’t expect a signed result.
Gotcha 2: missing keys return 0 (a double-edged sword)
The friendly tally["maybe"] == 0 behavior is great for tallies, but it also hides typos:
tally = Counter(["yes", "no"])
print(tally["ye"]) # 0, silently — looks like a real result
When correctness depends on the key existing, check membership ("ye" in tally) rather than trusting a zero.
Gotcha 3: update() increments, it does NOT replace
This is the one that fools seasoned Python devs. On a dict, update() replaces values. On a Counter, update() adds counts:
c = Counter("aab")
c.update("a") # increments, like +=
print(c) # Counter({'a': 3, 'b': 1})
# contrast with a plain dict:
d = {"a": 1, "b": 1}
d.update({"a": 99})
print(d) # {'a': 99, 'b': 1} -> dict replaces
Want to reset counts? Reassign the key (c["a"] = 0) or build a fresh Counter. Use update() only when you mean “add more occurrences.”
Gotcha 4: elements() skips zeros and negatives
elements() expands a Counter back into a multiset of individual items — but it omits anything at or below zero, and there is no guaranteed order:
c = Counter(a=2, b=0, c=-1)
print(list(c.elements())) # ['a', 'a'] -> b and c are skipped
When to reach for Counter
- Counting occurrences of hashable items (words, status codes, votes).
- Set-like math on multisets (
+,-,&,|). most_common(n)leaderboard queries.
Reach for a plain dict (or defaultdict(int)) when keys are unhashable, when you need replacement-style update, or when negative/zero entries must be preserved.
Cheat sheet
+/-do signed math;-drops non-positive keys.&= element-wise min,|= element-wise max.update()adds counts; to replace, assign directly.- Missing keys yield
0, neverKeyError. - Items must be hashable (tuples, not lists).