DEV Community

qing
qing

Posted on • Edited on

TIL: Python's `collections.Counter` makes frequency counting trivial (2026)

TIL: Python's collections.Counter makes frequency counting trivial

When working with datasets, counting the frequency of elements is a common task that can be tedious and error-prone if done manually. Python's collections.Counter class provides a convenient and efficient way to achieve this.

Here's a comparison between using Counter and a manual loop:


python
# Manual loop
fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana']
frequency = {}
for fruit in fruits:
    if fruit in frequency:
        frequency[fruit] += 1
    else:
        frequency[fruit] = 1

# Using Counter
from collections import Counter
fruits = ['apple',

---

*Follow me on Dev.to for daily Python tips and quick guides!*

---

*💡 Related: **Content Creator Ultimate Bundle (Save 33%)** — $29.99*

---

If you found this useful, you might like **[Python Automation Scripts Pack (10 Ready-to-Use Tools)](https://qssec.gumroad.com/l/python-automation-pack)** — a practical resource that takes things a step further. At $19.99 it's a solid investment for your toolkit.

---
喜欢这篇文章?关注获取更多Python自动化内容!
Enter fullscreen mode Exit fullscreen mode

Top comments (0)