← Back to all snippets
PYTHON

Count Frequencies of List Elements with collections.Counter

Discover how to quickly count the occurrences of hashable objects in a Python list using the powerful collections.Counter class for frequency analysis.

from collections import Counter

items = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple', 'grape']

# Count frequencies of all items
item_counts = Counter(items)
print(f"All item counts: {item_counts}")

# Access count for a specific item
apple_count = item_counts['apple']
print(f"Apple count: {apple_count}")

# Find the most common items
most_common_three = item_counts.most_common(3)
print(f"Top 3 most common items: {most_common_three}")

# Expected output:
# All item counts: Counter({'apple': 3, 'banana': 2, 'orange': 1, 'grape': 1})
# Apple count: 3
# Top 3 most common items: [('apple', 3), ('banana', 2), ('orange', 1)]
How it works: The `collections.Counter` class is a powerful tool for counting hashable objects. It's a subclass of `dict` that stores elements as dictionary keys and their counts as dictionary values. You can initialize it directly with an iterable, and it automatically tabulates frequencies. It also provides convenient methods like `most_common(n)` to retrieve the 'n' most frequent items and their counts, making it ideal for frequency analysis tasks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs