Editor

Python Program to Count Occurrences of an Element in a List

Beginner · Lists

The number of occurrences of a value is how many times it appears in a list. This program counts them with a loop and a counter, and reports the positions where the value was found.

Program

count_occurrences_in_list.py
numbers = [4, 2, 7, 4, 9, 4, 2, 1]
target = 4 # or: target = int(input("Enter the number to count: "))
count = 0
positions = []
for i in range(len(numbers)):
if numbers[i] == target:
count += 1
positions.append(i)
print("List:", numbers)
print(target, "appears", count, "times")
print("Found at indexes:", positions)
Output
List: [4, 2, 7, 4, 9, 4, 2, 1]
4 appears 3 times
Found at indexes: [0, 3, 5]

How it works

  1. count starts at 0 and goes up by 1 each time an element equals target.
  2. The loop runs over the indexes, so it can also note where each match is in positions.
  3. Here 4 is found at indexes 0, 3 and 5, so the count is 3.
  4. If the value is not in the list at all, the count stays 0 and positions stays empty.

Another way to write it

Using count()

Using count()
numbers = [4, 2, 7, 4, 9, 4, 2, 1]
print("4 appears", numbers.count(4), "times")
print("5 appears", numbers.count(5), "times")
fruits = ["apple", "Apple", "apple", "mango"]
print('"apple" appears', fruits.count("apple"), "times")
Output
4 appears 3 times
5 appears 0 times
"apple" appears 2 times

The list method count() does the counting in one call. It compares values exactly, so "Apple" with a capital A is not counted as "apple".

Try it yourself

Set target to 2, then to 8, and predict the count before you run it.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises