← Back to all snippets
PYTHON

Count Item Frequencies with `collections.Counter`

Quickly calculate the frequency of elements in a list, string, or iterator using `collections.Counter` in Python, ideal for analyzing user tags or search terms.

from collections import Counter

# Count occurrences in a list
fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple', 'grape']
fruit_counts = Counter(fruits)
print(f"Fruit counts: {fruit_counts}")

# Count character frequencies in a string
text = "hello world"
char_counts = Counter(text)
print(f"Character counts: {char_counts}")

# Get most common items
most_common_fruits = fruit_counts.most_common(2)
print(f"2 most common fruits: {most_common_fruits}")

# Perform arithmetic operations (e.g., combine counts)
c1 = Counter(a=3, b=1)
c2 = Counter(a=1, b=2)
combined_counts = c1 + c2
print(f"Combined counts (c1+c2): {combined_counts}")
How it works: `collections.Counter` is a specialized dictionary subclass for counting hashable objects. It's incredibly efficient for frequency analysis, such as determining the most common words in a text, top tags, or popular items in an e-commerce platform. It provides convenient methods like `most_common()` to retrieve the elements with the highest frequencies and supports arithmetic operations to combine or subtract counts, making data aggregation tasks straightforward.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs