PYTHON

Count Item Frequencies in a List Using collections.Counter

Discover how to quickly and efficiently count the occurrences of items in a Python list or any iterable using the specialized collections.Counter object.

from collections import Counter

my_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple', 'grape', 'orange']

# Create a Counter object from the list
item_counts = Counter(my_list)

print(f"All item counts: {item_counts}")

# Access count for a specific item
print(f"Count of 'apple': {item_counts['apple']}")
print(f"Count of 'pear' (non-existent): {item_counts['pear']}") # Returns 0 for non-existent items

# Find the N most common items
most_common_items = item_counts.most_common(2)
print(f"2 most common items: {most_common_items}")

# Get all unique items (keys)
print(f"Unique items: {list(item_counts.keys())}")
How it works: The `collections.Counter` object is a specialized dictionary subclass designed for counting hashable objects. It's incredibly useful for frequency analysis, providing a concise way to count occurrences in any iterable. When created with an iterable, it maps elements to their counts. You can access individual counts like a dictionary, and it conveniently returns 0 for non-existent items. The `most_common()` method allows retrieving the N highest-frequency items.

Need help integrating this into your project?

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

Hire DigitalCodeLabs