DEV Community

qing
qing

Posted on

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

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

As developers, we often find ourselves needing to count the frequency of elements in a list. This can be a tedious task, especially when dealing with large datasets. However, Python's collections module provides a simple and efficient solution: collections.Counter.

Let's consider an example where we have a list of numbers and we want to count the frequency of each number. We can achieve this using a manual loop:


python
numbers = [1, 2, 2, 3, 3, 3]
freq = {}
for num in numbers:
    if num in freq:
        freq[num] += 1
    else:
        freq[num]

---

*Follow me on Dev.to for daily Python tips and quick guides!*
Enter fullscreen mode Exit fullscreen mode

Top comments (0)