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
countstarts at 0 and goes up by 1 each time an element equalstarget.- The loop runs over the indexes, so it can also note where each match is in
positions. - Here 4 is found at indexes 0, 3 and 5, so the count is 3.
- If the value is not in the list at all, the count stays 0 and
positionsstays 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.
Related programs
- Count the Frequency of Each Element in a List
- Find Duplicates in a List
- Search for an Element in a List
- Count Occurrences of a Character in a String
- Find the Largest and Smallest Number in a List
- Swap Elements at Even and Odd Positions in a List
- Find the Second Largest Number in a List
- Remove Duplicates from a List
- a Menu-Driven List
- Find the Sum of Elements in a List
All Python programs · CBSE class 12 practical file · Python exercises