Using `collections.Counter` to Count Items in One Line

Published:
Last updated:
ByJeferson Peter
1 min read
Python
Share this post:

Counting occurrences is one of those tasks that appears everywhere:
log analysis, data cleaning, frequency tables, validations.

While it’s easy to do this manually with dictionaries, Python offers a better tool for the job: collections.Counter.


The manual counting approach

A very common pattern looks like this:

items = ["apple", "banana", "apple", "orange", "banana", "apple"]

counts = {}
for item in items:
    counts[item] = counts.get(item, 0) + 1

This works, but it’s boilerplate-heavy and hides the real intent: counting things.


Counting with Counter

from collections import Counter

items = ["apple", "banana", "apple", "orange", "banana", "apple"]

counts = Counter(items)
print(counts)
# Counter({'apple': 3, 'banana': 2, 'orange': 1})

The intent is immediately clear, and the code is shorter and more expressive.


Accessing counts safely

counts["apple"]
# 3

counts["pear"]
# 0

Missing keys return 0 instead of raising a KeyError, which is often exactly what you want.


Useful Counter methods

counts.most_common(2)
# [('apple', 3), ('banana', 2)]

This makes it easy to extract insights without extra logic.


A common mistake to avoid

Counter is optimized for counting, not for complex transformations.

# Not ideal
Counter(x.lower().strip() for x in data if x)

If preprocessing is complex, clean the data first, then count.


Conclusion

In real-world code, Counter improves both clarity and intent.

Whenever you find yourself manually incrementing dictionary values, it’s usually a sign that collections.Counter is the right tool.

Share this post: