The count()
method returns the number of times the specified element appears in the tuple.
Example
# tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'i', 'u')
# counts the number of i's in the tuple
count = vowels.count('i')
print(count)
# Output: 2
count() Syntax
The syntax of the count()
method is:
vowels.count('i')
Here, vowels is the tuple and 'i' is an element to count.
count() Parameter
The count()
method takes a single parameter:
- 'i' - an element to count in the tuple
count() Return Value
The count()
method returns:
- a number of times the given element
i
is present in the tuple
Example 1: Python Tuple count()
# tuple of numbers
numbers = (1, 3, 4, 1, 6 ,1 )
# counts the number of 1's in the tuple
count = numbers.count(1)
print('The count of 1 is:', count)
# counts the number of 7's in the tuple
count = numbers.count(7)
print('The count of 7 is:', count)
Output
The count of 1 is: 3 The count of 7 is: 0
In the above example, we have used the count()
method to count the number of times the elements 1 and 7 appear in the tuple.
Here, the tuple numbers tuple (1,3,4,1,6,1)
contains three 1's and doesn't contain the number 7. Hence, its count in the tuple is 3 and 0 respectively.
Example 2: count() to Count List and Tuple Elements Inside Tuple
# tuple containing list and tuples
random = ('a', ('a', 'b'), ('a', 'b'), [3, 4])
# count element ('a', 'b')
count = random.count(('a', 'b'))
print("The count of tuple ('a', 'b') is:", count)
# count element [3, 4]
count = random.count([3, 4])
print("The count of list [3, 4] is:", count)
Output
The count of tuple ('a', 'b') is: 2 The count of list [3, 4] is: 1
In the above example, we have used the count()
method to count the number of lists and tuples inside the tuple random.
The tuple ('a', 'b')
appears twice and the list [3, 4]
appears once. Hence, its count in the tuple is 2 and 1 respectively.
Also Read: