PYTHON
Count Element Frequencies Using `collections.Counter`
Discover how to efficiently count the occurrences of items in a list, string, or any iterable using Python's powerful `collections.Counter` class.
from collections import Counter
# Count frequencies in a list
data_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
list_counts = Counter(data_list)
print(f"List item counts: {list_counts}")
# Count character frequencies in a string
text_string = "programming"
char_counts = Counter(text_string)
print(f"Character counts: {char_counts}")
# Accessing counts and most common elements
print(f"Count of 'apple': {list_counts['apple']}")
print(f"Top 2 most common: {list_counts.most_common(2)}")
# Performing arithmetic operations (addition)
another_list = ['apple', 'grape']
another_counts = Counter(another_list)
total_counts = list_counts + another_counts
print(f"Combined counts: {total_counts}")
How it works: The `collections.Counter` class is a specialized dictionary subclass for counting hashable objects. It's incredibly useful for quickly determining the frequency of items in any iterable. It provides convenient methods like `most_common()` to retrieve elements by their counts and supports arithmetic operations for combining counts, making it a powerful tool for data analysis.