Click for All Topics
.count()
method is used to find the number of occurrences of an element in a list..count()
method with a list and pass an element then it initializes a counter variable in the backend with value 0 and it will traverse each element of the list and compare with the passed element, if the element is equal then it increases the value of the counter variable by 1 ,same process is done until the entire list is not traversed and then it returns the value of the counter variable.Syntax –
list.count(element)
Parameters –
Example 1-
my_list=[10,20,30,10,40,10,50,60,70]
count_of_10=my_list.count(10)
print("appearances of 10 in my_list:",count_of_10)
# Output -
# appearances of 10 in my_list: 3
.count()
method and store the result in the count_of_10 variable.
my_list=['a','b','c','d','e','f']
res=my_list.count('g')
print("Count of 'g' in my_list",res)
# Output -
# Count of 'g' in my_list: 0
Example 3- Count on empty list
my_list=[]
res=my_list.count(1)
print("Count of 1 in my_list:",res)
# Output -
# Count of 1 in my_list: 0
Example 4- Remove all duplicate element using .count()
method
my_list=[1,2,3,4,1,1,5,6,7,8]
print("Original list:",my_list)
while(my_list.count(1)>1):
my_list.remove(1)
print("Cleaned list:",my_list)
# Output -
# Original list: [1, 2, 3, 4, 1, 1, 5, 6, 7, 8]
# Cleaned list: [2, 3, 4, 1, 5, 6, 7, 8]
Example 5- count the occurrences of element without using in-built(.count()
) method
lst=['a','b','c','d','e','a','f','g']
c=0
for i in lst:
if i=='a':
c=c+1
print("Count of 'a' in my_list:",c)
# Output -
# Count of 'a' in my_list: 2
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India