Counts the number of occurrences of an item
Usage
Use count()
method to find the number of times the given item appears in the tuple.
Syntax
tuple.count(item)
Parameter | Condition | Description |
item | Required | Any item (of type string, list, set, etc.) you want to search for. |
Examples
# Count the number of occurrences of βredβ
T = ('red', 'green', 'blue')
print(T.count('red'))
# Prints 1
# Count the number of occurrences of number β9β
T = (1, 9, 7, 3, 9, 1, 9, 2)
print(T.count(9))
# Prints 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.
# Count occurrences of all the unique items
T = ('a', 'b', 'c', 'b', 'a', 'a', 'a')
from collections import Counter
print(Counter(T))
# Prints Counter({'a': 4, 'b': 2, 'c': 1})