Click for All Topics
.count()
method takes an element as an argument that you want to count and returns the count of a particular element..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 –
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
.count()
method and store the result in the count_of_3 variable.
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
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
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India