PYTHON
Count Element Frequencies with `collections.Counter`
Learn to efficiently count the occurrences of items in a list or string using Python's `collections.Counter`, ideal for data analysis and frequency distributions.
from collections import Counter
data = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple', 'grape']
# Count frequencies of elements in a list
fruit_counts = Counter(data)
print(f"Fruit counts: {fruit_counts}")
# Accessing counts
print(f"Count of 'apple': {fruit_counts['apple']}")
# Find the most common elements
most_common_fruits = fruit_counts.most_common(2)
print(f"Top 2 most common fruits: {most_common_fruits}")
# Counter can also be used with strings
text = "hello world"
char_counts = Counter(text)
print(f"Character counts: {char_counts}")
How it works: The `collections.Counter` class is a subclass of `dict` that is specifically designed for counting hashable objects. It provides a convenient way to count the frequency of elements in an iterable. You can initialize a Counter with a list, tuple, string, or any iterable. It automatically maps elements to their counts. The `most_common()` method allows you to easily retrieve the N most frequent elements and their counts. It's highly optimized for frequency counting tasks.