← Back to all snippets
PYTHON

Count Frequencies of Items with Python's `collections.Counter`

Learn to efficiently count the occurrences of items in a list or string using `collections.Counter`, ideal for data analysis or processing user inputs.

from collections import Counter

# Example 1: Counting elements in a list
data_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple', 'grape']
list_counts = Counter(data_list)
print(f"List item counts: {list_counts}")
# Access counts
print(f"Count of 'apple': {list_counts['apple']}")
print(f"Most common items: {list_counts.most_common(2)}")

# Example 2: Counting characters in a string
text_data = "hello world from python"
char_counts = Counter(text_data)
print(f"Character counts: {char_counts}")
print(f"Count of 'o': {char_counts['o']}")

# Example 3: Counting words in a sentence
sentence = "this is a test sentence this is another test"
words = sentence.split()
word_counts = Counter(words)
print(f"Word counts: {word_counts}")
How it works: The `collections.Counter` is a subclass of `dict` designed for counting hashable objects. It can be initialized with an iterable (like a list or string), and it automatically tallies the frequency of each unique item. You can access counts like a regular dictionary, find the most common items using `most_common()`, and even perform set-like operations (addition, subtraction) on Counter objects.

Need help integrating this into your project?

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

Hire DigitalCodeLabs