In this tutorial, we’ll learn how to properly use Python tuple count() method with the help of multiple Python code examples.
Introduction: Python Tuple count() Method
This method is used to return the number of times a specific item is used/appeared inside Python tuple.
For instance, if an integer 5 is used 3 times inside tuple then the count() method will return 3 if this integer 5 is passed to it as an argument.
Syntax of count() Method
tupleName.count(value)
- Python tuple count() method takes one argument and that is the value(item of a tuple).
- It returns an integer which specifies the number of times this item is appeared inside Python tuple.
Example 1: Count specific item inside Python Tuple
tupleItems=(1,2,3,4,6,2,5.4,2) print(tupleItems.count(2))
Output
3
The method shows that integer(2) has appeared 3 times in tuple.
Let’s used a Python list inside tuple as well. See below code:
tupleItems=(1,2,3,4,[2,5],6,2,5.4,2) print(tupleItems.count(2))
Output
3
We can see that the value(2) is present inside a list as well but its not counted. Reason is that this list is counted as a single item.
Example 2: Count Lists and Tuples inside Python Tuple
tupleItems=(1,2,[2,5],6,[2,5],2,(5.4,2),(5,7)) print( tupleItems.count([2,5]) ) print( tupleItems.count((5.4,2)) )
Output
2 // list with same specified elements appears 2 times inside tuple 1 // tuples with specified elements appears only 1 time inside tuple
We can pass list or tuple inside count method to get the number of times they are appeared inside Python tuple (having same values).
Example 3: count() Method Return Value
tupleItem=['white','green','blue','white','purple','white'] returnedValue=tupleItem.count('white') print(returnedValue)
Output
3 // string(white) appears 3 times inside tuple so the number is returned
Python tuple count() method returns the number of times a specific item appears inside Python tuple.
Example 4: Specified Item not Found in Tuple
tupleItem=['white','green','blue','white','purple','white'] print(tupleItem.count('orange'))
Output
0
This method returns 0 if the item passed to it is not found in tuple.
Conclusion
In conclusion, now you have a practical code knowledge of how to easily use Python tuple count method. I’ll be very glad to receive your feedback. Thank you for reading this post.