Python Tuple count() Function Example
Python tuple count() is an inbuilt method that helps us to calculate the occurrence of one element present in the tuple and returns the counted number. The count() method searches the given component of a tuple and returns how many times the item has occurred in it.
Python Tuple count()
The count() function returns the number of times the specified value appears in the tuple.
Here, tuple_name is the name of the tuple, and the element is the element whose frequency is to be counted.
Python tuple count() method returns the number of occurrences of one element present in the tuple.
See the following code.
# app.py # Declaring tuple marks = (75, 64, 91, 67, 75, 64) # Now we will print the tuple print("Tuple values are: ", marks) # We will count the occurence of 75 and 64 print("Frequency of 75 is :", marks.count(75)) print("Frequency of 64 is :", marks.count(64)) # Printing total marks print("Total marks : ", sum(marks))
Tuple values are: (75, 64, 91, 67, 75, 64) Frequency of 75 is : 2 Frequency of 64 is : 2 Total marks : 436
In the above program, we have declared a tuple containing marks of a student, and we have printed that. After that, we have checked the frequency of 75, which means in how many subjects the student gt 75, same for 64. At last, we have printed the total marks the student got.
#Count the occurrences of item in a tuple
See the following code in which we count the vowels in the tuple.
# app.py vowels = ('a', 'e', 'i', 'o', 'u', 'a', 'e', 'i', 'o') # count element 'a' count = vowels.count('a') # print count print('The count of a is:', count) # count element 'k' count = vowels.count('k') # print count print('The count of k is:', count)
pyt python3 app.py The count of a is: 2 The count of k is: 0
In the above code, a character appears 2 times, so it returns 2, and k is not in the tuple so, it returns 0.
Python tuple count() method counts the occurrence of an element in the tuple. It returns the occurrence of the item passed during the call. It required a parameter which is to be counted. It returns an error if the parameter is missing.