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.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 10 views 0 copies

Python code

10 lines
Python 3.9+
from 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

stdout
{'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

  1. Use a dictionary comprehension with the list's `count` method for readability on small lists
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.