At times, it might be required to count the number of times a specific element has been seen in a tuple. This can be done in a variety of ways in Python. We will see a few of them here:
1. Using a counter
In this approach, we will have a counter that will keep a tab on the number of times that specific element was found in the tuple. Each time it is found, the counter is incremented.
Time for an example:
my_tuple = (0, 15, 26, 78, 89, 38, 93, 2, 26, 5, 26)
element_to_be_searched = 26
# initializing the counter
count = 0
for element in my_tuple:
if element == element_to_be_searched:
count += 1
print("The element " + str(element_to_be_searched) + " was found "+str(count)+" times")
Output:
The element 26 was found 3 times
2. Using the built-in count()
method
The built-in count()
method searches for the specified element in the python tuple and returns the count. It takes a single parameter (element whose count is to be found) and returns the occurrence.
Syntax of the count()
method:
tuple_name.count(element_to_be_counted)
Time for an example:
my_tuple = (0, 15, 26, 78, 89, 38, 93, 2, 26, 5, 26)
count = my_tuple.count(26)
print("The element was found "+str(count)+" times")
my_char_tuple = ('a', 'b', 's', 't', 'c', 's', 'u', 's', 's', 'm')
char_count = my_char_tuple.count('s')
print('The count of s is:', char_count)
Output:
The element was found 3 times
The count of s is: 4
Note: The built-in count()
method can also be used to count the number of times a list or a tuple has occurred inside a tuple. Below is an example demonstrating the same.
my_tuple = ('a', ['s', 't'], ['s', 'y'], ['s', 't'], (12, 0), ['s'])
count = my_tuple.count(['s', 't'])
print("The count is:", count)
count = my_tuple.count((12))
print("The count is:", count)
count = my_tuple.count((12,0))
print("The count is:", count)
Output:
The count is: 2
The count is: 0
The count is: 1
Conclusion
In this post, we understood how to obtain the count of a specific element inside a tuple. Don't forget to mention in the comments about how you would approach such a problem.