PYTHON
Efficiently Count Item Frequencies with collections.Counter
Learn to quickly count element frequencies in a list or string using Python's collections.Counter, ideal for data analysis and statistics tasks.
from collections import Counter
# Example 1: Counting elements in a list
my_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
item_counts = Counter(my_list)
print(f"List item counts: {item_counts}")
# Example 2: Counting characters in a string
my_string = "hello world"
char_counts = Counter(my_string)
print(f"Character counts: {char_counts}")
# Example 3: Finding most common elements
most_common = item_counts.most_common(2)
print(f"Two most common items: {most_common}")
How it works: The `collections.Counter` class is a specialized dictionary subclass for counting hashable objects. It's incredibly efficient for tallying occurrences of items in any iterable. When initialized with an iterable, it builds a dictionary where keys are the elements and values are their counts. It also provides useful methods like `most_common()` to quickly retrieve the n most frequent items.