Python List – count()
Python list.count(element) method returns the number of occurrences of the given element in the list.
Syntax
The syntax to call count() method on a list myList
is
</>
Copy
myList.count(element)
where
myList
is a Python listcount
is method nameelement
is the object to be searched for in the list
Examples
Count Element’s Occurrences in List
In the following program, we initialize a list myList
with some elements, and get the number of occurrences of the element 'apple'
in the list.
main.py
</>
Copy
#take a list
myList = ['apple', 'banana', 'apple', 'cherry']
#count 'apple' occurrences
n = myList.count('apple')
print(f'No. of occurrences : {n}')
Output
No. of occurrences : 2
Count Element’s Occurrences in List (Element not present in List)
Now, we shall take a list myList
, and count the occurrences of the element 'mango'
which is not present in the list. Since, the element is not present in the list, count() must return 0
.
main.py
</>
Copy
#take a list
myList = ['apple', 'banana', 'apple', 'cherry']
#count 'mango' occurrences
n = myList.count('mango')
print(f'No. of occurrences : {n}')
Output
No. of occurrences : 0
Conclusion
In this Python Tutorial, we learned how to find the number of occurrences of an element in the list using list.count() method.