Python tuple index()

Python tuple‘s index method find the element in the tuple and returns the index, if element is not present in the list then it will raise ValueError.


Syntax

Here tuple1 is object of the tuple and item is the element you want to search in the tuple.


Return

return index of the element but if element is not present in the tuple, it will raise ValueError.


Example

Let’s see a very simple example:

tupleOfFruits=('Orange','Banana','Apple') i=tupleOfFruits.index('Banana') print("Index of Banana:",i)

Output:

Index of Banana: 1

If element is not present in the tuple, then it will raise ValueError.

tupleOfVehicles=('Car','Truck','Bike') i=tupleOfVehicles.index('Cycle') print("Index of Banana:",i)

Output:

—————————————————————————
ValueError Traceback (most recent call last)
in ()
1 tupleOfVehicles=(‘Car’,’Truck’,’Bike’)
—-> 2 i=tupleOfVehicles.index(‘Cycle’)
3 print(“Index of Banana:”,i)

ValueError: tuple.index(x): x not in tuple

Let’s see how to get index of set which is inside the tuple.

tuple1=('One','two',{10,20,30,40},'three','four') i=tuple1.index({10,20,30,40}) print("Index of set in tuple:",i)

Output:

Index of set in tuple: 2

That’s all about Python tuple index() method.

Leave a Reply

Your email address will not be published. Required fields are marked *