Python Tuple count() Method

Counts the number of occurrences of an item


Use count() method to find the number of times the given item appears in the tuple.



Python tuple count() method parameters
itemRequiredAny item (of type string, list, set, etc.) you want to search for.


Example: Count the number of occurrences of β€˜red’

T = ('red', 'green', 'blue')
print(T.count('red'))	# 1

Example: Count the number of occurrences of number β€˜9’

T = (1, 9, 7, 3, 9, 1, 9, 2)
print(T.count(9))	# 3

Count Multiple Items

If you want to count multiple items in a tuple, you can call count() in a loop.

This approach, however, requires a separate pass over the tuple for every count() call; which can be catastrophic for performance.

Use couter() method from class collections, instead.

Example: Count occurrences of all the unique items

T = ('a', 'b', 'c', 'b', 'a', 'a', 'a')
from collections import Counter
print(Counter(T))    # Counter({'a': 4, 'b': 2, 'c': 1})