← Back to all snippets
PYTHON

Count Frequencies of Items Using `collections.Counter`

Efficiently count the occurrences of items in a list or other iterable using Python's `collections.Counter`, ideal for statistics and data analysis in web applications.

from collections import Counter

# Counting occurrences in a list of strings (e.g., user roles, tags)
items = ['admin', 'user', 'editor', 'user', 'admin', 'guest', 'user']
item_counts = Counter(items)
print(f"Item counts: {item_counts}")

# Counting characters in a string (e.g., text analysis)
text = "hello world"
char_counts = Counter(text)
print(f"Character counts: {char_counts}")

# Finding the most common items
most_common_items = item_counts.most_common(2)
print(f"2 most common items: {most_common_items}")
How it works: The `collections.Counter` class is a specialized dictionary subclass designed for counting hashable objects. It's incredibly useful for quickly determining the frequency of items in a list, characters in a string, or any other iterable. You can initialize a `Counter` directly from an iterable, and it will automatically tabulate the counts. The `most_common(n)` method allows you to easily retrieve the `n` most frequent items and their counts.

Need help integrating this into your project?

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

Hire DigitalCodeLabs