Python Tuple count() Method
The count()
returns the number of times a specified value appears in the tuple.
Syntax
tuple.count(value)
Parameter
value
: The item you want to count in the tuple.
Return Value
Returns the number of times the specified value appears in the tuple.
Example:
my_tuple = (1, 2, 3, 2, 4, 2)
print(my_tuple.count(2)) # Output: 3
In the above example, the value 2
appears three times in the my_tuple
. Therefore, count(2)
returns 3
.
Counting Strings
my_tuple = ("apple", "banana", "Apple", "mango", "apple")
print(my_tuple.count("apple")) # Output: 2
In the above example, "apple"
appears two times in the my_tuple
. The "Apple"
with an uppercase A
is considered different due to case sensitivity. Therefore, count("apple")
returns 2
.
If you want to count all the values in a tuple, you can use collections.Counter()
instead. It not only works with tuples, but with any iterable such as lists and strings.
from collections import Counter
my_tuple = (1, 2, 3, 2, 4, 2, 4)
print(Counter(my_tuple)) # Output: Counter({2: 3, 4: 2, 1: 1, 3: 1})