collections.Counter
Overview
`collections.Counter` is a dict subclass built for counting. Pass it any iterable and it tallies occurrences; it also adds counting-specific methods. from collections import Counter c = Counter('mississippi') # {'i':4,'s':4,'p':2,'m':1} c.most_common(2) # [('i', 4), ('s', 4)] c['x'] # 0 (missing key -> 0, no KeyError) c.update('sip') # add more counts Counters support arithmetic: `c1 + c2` adds counts, `c1 - c2` subtracts (dropping zero/negatives), and `&`/`|` give min/max intersections. `most_common(n)` returns the n highest-frequency items already sorted — the reason Counter shows up in almost every 'top-k frequent' problem.
Frequency analysis is a staple: word counts, top-k elements, detecting duplicates, comparing distributions. Counter replaces a manual dict-plus-loop with one line and gives you sorted top-k for free.
Where used: Word / event frequency analysis, Top-k frequent elements problems, Detecting duplicates and anagrams
Why learn this
- Counting frequencies and finding top-k elements are extremely common in data tasks and interviews.
- `most_common()` hands you sorted results without writing any sorting code.
Code walkthrough
from collections import Counter
c = Counter('mississippi')
print(c['s'])
print(c['z'])
print(c.most_common(2))
Focus: c['z'] prints 0 (missing element counts as zero, no KeyError)
Common mistakes
- Expecting KeyError for missing keys: Unlike a plain dict, `Counter()['missing']` returns `0` rather than raising. That's convenient, but it means a typo'd key silently reads as 0 instead of failing loudly.
- Thinking Counter subtraction can go negative: The `-` operator drops zero and negative results (`Counter({'a': 1}) - Counter({'a': 3})` gives an empty Counter, not `-2`). Use `.subtract()` if you actually want negative counts retained.
- Sorting manually for top-k: Writing `sorted(c.items(), key=..., reverse=True)[:k]` reinvents `c.most_common(k)`, which already returns the k most frequent items in order.
Glossary
- multiset
- A set that allows repeated elements and tracks how many times each appears. A `Counter` is Python's multiset. Example: `Counter('aab') -> {'a': 2, 'b': 1}`.
Recall questions
- What does `Counter('aabbbc')` produce, and what does `.most_common(1)` return?
- What does indexing a missing key on a Counter return?
- How does `Counter - Counter` handle a result that would be negative?
Understanding checks
What does this print?
[('a', 3)]
'banana' has a:3, n:2, b:1. `most_common(1)` returns the single highest-frequency element as a (element, count) tuple inside a list.
What is the resulting Counter?
Counter() (empty)
Counter's `-` keeps only positive counts. 1 - 3 = -2, which is dropped, leaving an empty Counter. To keep -2 you'd use `.subtract()`.
Practice tasks
Top-2 most common words
Given the sentence, count word frequencies with Counter and print the two most common words with their counts.
Continue learning
Previous: collections.defaultdict