How to Count Occurrences of Each Value in Python
Count how many times each value appears in a list using Python's Counter from the collections module.
Python code
10 linesfrom collections import Counter
def count_occurrences(values):
"""Return a dictionary mapping each value to its count."""
return dict(Counter(values))
if __name__ == "__main__":
sample_data = ["apple", "banana", "apple", "cherry", "banana", "apple"]
result = count_occurrences(sample_data)
print(result)
Output
{'apple': 3, 'banana': 2, 'cherry': 1}
How it works
The Counter class is a specialized dictionary designed for counting hashable objects. Counter(values) creates a counter object where keys are the unique elements and values are their counts. Converting it to a standard dictionary with dict() preserves the key-value pairs in insertion order (Python 3.7+). This approach is concise and efficient, O(n) time, and works with any iterable of hashable items.
Common mistakes
- Using a manual loop when `Counter` is simpler and faster
- Forgetting that `Counter` returns a subclass of dict, not a plain dict, if you don't convert it
- Assuming the method works with unhashable types like lists as elements
Variations
- Use a dictionary comprehension with the list's `count` method for readability on small lists
- Use `collections.defaultdict(int)` to increment counts manually when you need fine-grained control
Real-world use cases
- Analyzing log files to find the most frequent error codes or IP addresses.
- Building recommendation features by counting how often users purchase each product.
- Validating data integrity by checking the frequency of duplicate records in a dataset.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.