Python Tuple Methods
Python Tuples is an immutable collection of that are more like lists. Python Provides a couple of methods to work with tuples. In this article, we will discuss these two methods in detail with the help of some examples.
The count() method of Tuple returns the number of times the given element appears in the tuple.
Where the element is the element that is to be counted.
Example 1: Using the Tuple count() method
Count of 3 in Tuple1 is: 3 Count of Python in Tuple2 is: 3
Example 2: Counting tuples and lists as elements in Tuples
Count of (2, 3) in Tuple is: 2 Count of [3, 2] in Tuple is: 1
The Index() method returns the first occurrence of the given element from the tuple.
tuple.index(element, start, end)
- element: The element to be searched.
- start (Optional): The starting index from where the searching is started
- end (Optional): The ending index till where the searching is done
Note: This method raises a ValueError if the element is not found in the tuple.
Example 1: Using Tuple Index() Method
First occurrence of 3 is 3 First occurrence of 3 after 4th index is: 5
Example 2: Using Tuple() method when the element is not found
ValueError: tuple.index(x): x not in tuple
Note: For more information on Python Tuples refer to Python Tuple Tutorial.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course