How to Count Occurrences of a Value in a Python List

Counts how many times a specific value appears in a list using a simple loop and a counter variable.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 13 views 0 copies

Python code

13 lines
Python 3.9+
def count_occurrences(data, target):
    count = 0
    for item in data:
        if item == target:
            count += 1
    return count


if __name__ == "__main__":
    numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
    target_value = 5
    result = count_occurrences(numbers, target_value)
    print(f"The value {target_value} appears {result} times in {numbers}")

Output

stdout
The value 5 appears 3 times in [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

How it works

The function initializes a counter at zero, then loops over every item in the list. Each time an item equals the target value, the counter is incremented by one. After the loop finishes, the counter holds the exact number of matches, which is returned. This is a straightforward O(n) approach that works on any iterable, not just lists.

Common mistakes

  • Comparing items with `is` instead of `==` for values
  • Forgetting to reset the counter on each function call
  • Using the list's `count` method inside a loop, which duplicates work

Variations

  1. Use the built-in `list.count()` method: `numbers.count(5)`
  2. Use a list comprehension with `sum`: `sum(1 for item in data if item == target)`

Real-world use cases

  • Counting how many times a specific product was sold in a sales log for daily reporting.
  • Analyzing survey responses to tally how often a particular answer choice was selected.
  • Checking a list of log entries for repeated error codes to gauge issue frequency.

Sponsored

Run this sample

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

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.