PYTHON
Count Element Frequencies Efficiently
Learn to quickly count the occurrences of items in a list or any iterable using Python's collections.Counter, ideal for data analysis and statistics.
from collections import Counter
data = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
fruit_counts = Counter(data)
print(f"Original data: {data}")
print(f"Fruit counts: {fruit_counts}")
print(f"Count of 'apple': {fruit_counts['apple']}")
# Common patterns
print(f"Most common elements: {fruit_counts.most_common(2)}")
How it works: The collections.Counter object is a specialized dictionary subclass for counting hashable objects. When initialized with an iterable, it stores elements as keys and their counts as values. It provides convenient methods like most_common() to retrieve the most frequent elements, making it highly efficient for frequency analysis.