Python

count() method in list

Click for All Topics

count() method in list - Python

  • The .count() method is used to find the number of occurrences of an element in a list.
  • This method takes exactly one argument and returns the number of appearances of an element in a list.
  • When you call this method with a list and pass an element that doesn’t exist in the list, then it returns 0.
  • When you call the .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.
  • The time complexity of this method is O(n).

 

Syntax –

list.count(element)

 

Parameters –

  • element → element that’s occurrences you want to count.
  • return → return appearances of the passed element in the list.

 

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
				
			
  • In the above example first, we create a list with some elements and store it in my_list variable.
  • Then find the occurrences of 10 in my_list using the .count() method and store the result in the count_of_10 variable.
  • Finally, print the result on the output screen.
Example 2- Count the appearances of the element that doesn’t exist
				
					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