collections.Counter

RoadmapsPython

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

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

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

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

Return to Python Roadmap