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.
Python code
13 linesdef 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
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
- Use the built-in `list.count()` method: `numbers.count(5)`
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.