Counting with Counter
Counting is a pattern that appears everywhere—from analyzing word frequencies in a dataset to counting user interactions or summarizing event logs. Python could certainly do this with a dictionary and some careful checks, but the Counter class in collections removes the boilerplate entirely by treating counting as a first-class operation.
Counter can be called as:
Counter(iterable)
Counter(mapping)
Where iterable is anything you can loop over (list, string, generator), and mapping is a dict-like object of element:count pairs.
Consider word frequency analysis:
from collections import Counter
text = "to be or not to be that is the question"
counts = Counter(text.split())
print(counts)
print(counts.most_common(2))Output
Counter({'to': 2, 'be': 2, 'or': 1, 'not': 1, 'that': 1, 'is': 1, 'the': 1, 'question': 1})
[('to', 2), ('be', 2)]
most_common(n) returns the top n items as (element, count) tuples which is extremely useful in text mining or exploratory analysis.
Another example from log analysis:
errors = ["500", "404", "404", "503", "500", "500"]
print(Counter(errors))Output
Counter({'500': 3, '404': 2, '503': 1})
The output shows how often each error code appeared—an immediate snapshot of system behavior.