collections.Counter
Hand it an iterable and it counts; hand it a mapping and it takes the counts as given. Reading a missing element gives 0 instead of KeyError, and + - & | work on whole counters.
Demo
from collections import Counter Counter('mississippi')
In the repr, equal counts keep first-seen order: for "mississippi", i and s both appear 4 times and i comes first because it is met first. Subtraction and intersection drop anything that ends at zero or below, which is why a - b for "same" is an empty Counter(). A missing key reads as 0 but "key in c" stays False and len(c) does not grow.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| iterable | iterable | mapping | no (None) | Elements to count, or a mapping of element → count (taken as-is, zero and negative counts included). |
| **kwds | int | no | Counts given as keyword arguments: Counter(a=2, b=1). |
Return value
Counter — A new counter: each distinct element maps to how many times it was seen.
Common patterns
from collections import Counter freq = Counter(text.lower().split()) freq.most_common(5)
from collections import Counter by_ext = Counter(name.rsplit(".", 1)[-1] for name in filenames)
from collections import Counter can_build = Counter(word) <= Counter(letters)
from collections import Counter total = sum((Counter(batch) for batch in batches), Counter())
Examples
Pitfalls
from collections import Counter Counter('hi hi').most_common(1)
from collections import Counter Counter('hi hi'.split()).most_common(1)
from collections import Counter Counter(a=1) - Counter(a=3)
from collections import Counter c = Counter(a=1) c.subtract(Counter(a=3)) c
from collections import Counter Counter(a=1) + {'a': 1}
from collections import Counter c = Counter(a=1) c.update({'a': 1}) c
When to use
- Counting occurrences of anything hashable
- Top-N rankings with most_common()
- Multiset maths: combining, differencing, subset tests
- Counting a single value in a list → list.count(x)
- Weighted or fractional tallies with negative values you want kept through + and - → a plain dict
Notes
FAQ
collections.Counter(my_list) returns a dict-like object mapping each item to its count; counter.most_common(n) gives the n most frequent. For a single item, my_list.count(item) is enough.