Given a list in Python and a number x, count number of occurrences of x in the given list.
Examples:
Input : lst = [15, 6, 7, 10, 12, 20, 10, 28, 10]
x = 10
Output : 3
10 appears three times in given list.
Input : lst = [8, 6, 8, 10, 8, 20, 10, 8, 8]
x = 16
Output : 0
Method 1 (Simple approach)
We keep a counter that keeps on increasing if the esquired element is found in the list.
# Python code to count the number of occurrences def countX(lst, x): count = 0 for ele in lst: if (ele == x): count = count + 1 return count # Driver Code lst = [8, 6, 8, 10, 8, 20, 10, 8, 8] x = 8print('{} has occurred {} times'.format(x, countX(lst, x))) |
Output: 8 has occurred 5 times
Method 2 (Using count())
The idea is to use list method count() to count number of occurrences.
# Python code to count the number of occurrences def countX(lst, x): return lst.count(x) # Driver Code lst = [8, 6, 8, 10, 8, 20, 10, 8, 8] x = 8print('{} has occurred {} times'.format(x, countX(lst, x))) |
Output: 8 has occurred 5 times
Method 2 (Using Counter())
Counter method returns a dictionary with occurrences of all elements as a key-value pair, where key is the element and value is the number of times that element has occurred.
from collections import Counter # declaring the list l = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5] # driver program x = 3d = Counter(l) print('{} has occurred {} times'.format(x, d[x])) |
Output: 3 has occurred 2 times
Recommended Posts:
- Remove all the occurrences of an element from a list in Python
- Python | Count occurrences of an element in a Tuple
- Python | Count String occurrences in mixed list
- Python | Remove all occurrences in nested list
- Python - All occurrences of Substring from the list of strings
- Python | Count occurrences of a character in string
- Python | Count occurrences of each word in given text file (Using dictionary)
- Python program to Count the Number of occurrences of a key-value pair in a text file
- Count occurrences of a word in string
- Python | Deleting all occurrences of character
- Python | Get the starting index for all occurrences of given substring
- Python | All occurrences of substring in string
- Python | Record Similar tuple occurrences
- Python - Extract elements with Range consecutive occurrences
- Python - Characters Index occurrences in String
- Python - Replace all repeated occurrences with N
- Python | Replace characters after K occurrences
- Python - Distance between occurrences
- Python - Replace all occurrences of a substring in a string
- Python - Retain records with N occurrences of K
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

