Python | Count occurrences of an element in a list
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 occurences 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:
- Python | Count occurrences of an element in a Tuple
- Python | Count the sublists containing given element in a list
- Python | Count the elements in a list until an element is a Tuple
- Python | Remove all occurrences in nested list
- Python | Count occurrences of a character in string
- Python | Count occurrences of each word in given text file (Using dictionary)
- Python | Replace elements in second list with index of same element in first list
- Python | Indices list of matching element from other list
- Python | Slicing list from Kth element to last element
- Python | Move one list element to another list
- Python | Three element sum in list
- Python | How to get the last element of list
- Python | Every Kth element in list
- Python | Insert after every Nth element in a list
- Python | Removing first element of list
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.



