Python

count() method in tuple

Click for All Topics

count() method in tuple - Python

  • This method is used to count the occurrences of a specified element in a tuple.
  • The .count() method takes an element as an argument that you want to count and returns the count of a particular element.
  • It will return zero when an element doesn’t exist in the tuple.
  • The time complexity of this method is O(n) where n is the number of elements in a tuple.
  • When you call the .count() method with a tuple and pass an element then it initializes a counter variable in the backend with value 0 and it will traverse each element of the tuple 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 tuple is not traversed and then it returns the value of the counter variable.

Syntax –

tuple.count(element)

Parameters –

  • element → element whose apperance you want to count.
  • return → return number of apperances of an element in the tuple

Example  1-

				
					my_tuple = (1,2,3,4,3,3,5,3)
print("My Tuple :",my_tuple)
count_of_3=my_tuple.count(3)
print("Appearances of 3 are:",count_of_3)

# Output -
# My Tuple : (1, 2, 3, 4, 3, 3, 5, 3)
# Appearances of 3 are: 4
				
			
  • In the above example first, we create a tuple with some elements and store it in the my_tuple variable.
  • After creating my_tuple print the my_tuple on the output screen.
  • Then find the occurrences of 3 in my_tuple using the .count() method and store the result in the count_of_3 variable.
  • finally, print the result on the output screen.
Example 2- count the appearances of an element that doesn’t exist in the tuple
				
					my_tuple = ('hello', 'python', 'tuple', 'methods')
result=my_tuple.count('anurag')
print("Count of 'anurag' in my_tuple:",result)

# Output -
# Count of 'anurag' in my_tuple: 0
				
			
Example 3- count on empty tuple
				
					tuple1=()
result=tuple1.count(0)
print(result)

# Output -
# 0
				
			

Example 4- count the occurrence of a particular element in a tuple without using an in-built method

				
					my_tuple=('a','b','c','a','d','a','e')
count_of_a=0
for i in my_tuple:
	if i=='a':
		count_of_a+=1
print("count of 'a' in my_tuple:",count_of_a)

# Output -
# count of 'a' in my_tuple: 3