Python Tuple – count()

Python tuple.count(element) method returns the number of occurrences of the given element in the tuple.

Syntax

The syntax to call count() method on a tuple myTuple is

</>
Copy
myTuple.count(element)

where

  • myTuple is a Python tuple
  • count is method name
  • element is the object to be searched for in the tuple

Examples

1. Count Element’s Occurrences in Tuple

In the following program, we initialize a tuple myTuple with some elements, and get the number of occurrences of the element 'apple' in the tuple.

main.py

</>
Copy
#take a tuple
myTuple = ('apple', 'banana', 'apple', 'cherry')

#count 'apple' occurrences
n = myTuple.count('apple')

print(f'No. of occurrences : {n}')

Output

No. of occurrences : 2

Count Element’s Occurrences in Tuple (Element not present in Tuple)

Now, we shall take a tuple myTuple, and count the occurrences of the element 'mango' which is not present in the tuple. Since, the element is not present in the tuple, count() must return 0.

main.py

</>
Copy
#take a tuple
myTuple = ('apple', 'banana', 'apple', 'cherry')

#count 'mango' occurrences
n = myTuple.count('mango')

print(f'No. of occurrences : {n}')

Output

No. of occurrences : 0

Conclusion

In this Python Tutorial, we learned how to find the number of occurrences of an element in the tuple using tuple.count() method.