DEV Community

qing
qing

Posted on

Quick Python Tip: collections.Counter Makes Frequency Counting Trivial

Quick Python Tip: collections.Counter Makes Frequency Counting Trivial
When working with datasets, frequency counting is a common task that can be cumbersome to implement manually. However, Python's collections module provides a simple and efficient solution with the Counter class.

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

from collections import Counter

# Manual loop
fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana']
freq = {}
for fruit in fruits:
    if fruit in freq:
        freq[fruit] += 1
    else:
        freq[fruit] = 1
print(freq)

# Using Counter
fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana']
freq = Counter(fruits)
print(freq)
Enter fullscreen mode Exit fullscreen mode

As you can see, Counter achieves the same result in just one line of code, making it a much more concise and readable solution.

By leveraging collections.Counter, you can simplify your frequency counting tasks and focus on more complex aspects of your project, making your code more efficient and Pythonic.


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


🛠️ Recommended Tool

If you found this useful, check out Content Creator Ultimate Bundle (Save 33%) — $29.99 and designed for developers like you.

Get instant access to our best-selling AI Dev Boost, HTML Landing Page Templates, AI Prompts for Developers, and Python Automation Scripts Pack, perfect for content creators and marketers looking to elevate their game. This bundle is a must-have for anyone looking to create stunning content, build high-converting landing pages, and drive real results. With these tools, you'll be able to create engaging content, build beautiful landing pages, and boost your online presence.

Top comments (0)