PYTHON

Counting Element Frequencies with collections.Counter

Efficiently count the occurrences of hashable items in a list or any iterable using Python's `collections.Counter` for frequency analysis, statistics, or data summarization.

from collections import Counter

# Example 1: Counting items in a list of strings
words = ["apple", "banana", "apple", "orange", "banana", "apple", "grape"]
word_counts = Counter(words)
print(f"Word counts: {word_counts}") # Output: Counter({'apple': 3, 'banana': 2, 'orange': 1, 'grape': 1})

# Accessing individual counts
print(f"Count of 'apple': {word_counts['apple']}")
print(f"Count of 'mango' (not present): {word_counts['mango']}") # Returns 0 for missing keys

# Example 2: Counting items from a list of numbers
numbers = [1, 2, 2, 3, 1, 4, 2, 5, 5, 5]
number_counts = Counter(numbers)
print(f"Number counts: {number_counts}")

# Finding the N most common elements
print(f"Two most common words: {word_counts.most_common(2)}")
print(f"One most common number: {number_counts.most_common(1)}")

# Operations like addition/subtraction are also possible
more_words = ["apple", "grape", "kiwi"]
word_counts.update(more_words) # Adds counts from another iterable
print(f"Word counts after update: {word_counts}")
How it works: The `collections.Counter` is a subclass of `dict` specifically designed for counting hashable objects. It provides a convenient way to get the frequency distribution of elements in an iterable. You can initialize it with a list or string, access counts like a dictionary (returning 0 for missing keys instead of raising a `KeyError`), and use methods like `most_common()` to retrieve the most frequent items. It's incredibly useful for frequency analysis, vote counting, or summarising data efficiently.

Need help integrating this into your project?

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

Hire DigitalCodeLabs