Python Tuple – index()

Python Tuple index() method returns the index of the specified element, that is passed as argument, in the calling tuple.

If the element is not at all present in the tuple, then it throws ValueError.

In this tutorial, we will learn how to use tuple.index() method, when there is one occurrence, multiple occurrences, or no occurrence of the specified element in the tuple.

Syntax

The syntax to call index() method on a tuple myTuple is

</>
Copy
myTuple.index(element)

where

  • myTuple is the tuple of elements.
  • index is the name of the method.
  • element is the one whose index in the tuple is to be found.

Examples

1. Single occurrence of element in Tuple

In this example, we will take a tuple of strings myTuple, and find the index of 'mango' in this tuple.

main.py

</>
Copy
myTuple = ('apple', 'banana', 'cherry', 'orange', 'mango', 'kiwi')
index = myTuple.index('mango')
print(f'index : {index}')

Output

index : 4

2. Multiple occurrences of element in the Tuple

When the element, whose index we are trying to find, occurs multiple times in the tuple, index() method returns the index of first match and ignores the other occurrences.

In the following program, we take a tuple where element 'mango' occurs twice in the tuple. We find the index of the element 'mango' in the tuple, using tuple.index() method.

main.py

</>
Copy
myTuple = ('apple', 'banana', 'mango', 'cherry', 'orange', 'mango', 'kiwi')
ind = myTuple.index('mango')
print(ind)

Output

2

3. No occurrences of element in Tuple

When there is no occurrence of element, whose index we are trying to find in the tuple, tuple.index() throws ValueError.

main.py

</>
Copy
myTuple = ('apple', 'banana', 'mango')
ind = myTuple.index('watermelon')
print(ind)

Output

Traceback (most recent call last):
  File "example.py", line 2, in <module>
    ind = myTuple.index('watermelon')
ValueError: tuple.index(x): x not in tuple

This could terminate our program execution. So, how do we handle this?

Prior to making a call to index() method, check if element is present in the tuple.

main.py

</>
Copy
myTuple = ('apple', 'banana', 'mango')
element = 'watermelon'
if element in myTuple:
	ind = myTuple.index('watermelon')
	print(ind)
else:
    print(element, 'not in the tuple.')

Output

watermelon not in the tuple.

Or you can also use try except to handle ValueError thrown by tuple.index() method.

Python Program

</>
Copy
myTuple = ('apple', 'banana', 'mango')
element = 'watermelon'
try:
    ind = myTuple.index('watermelon')
    print(ind)
except ValueError as e:
    print(element, 'not in the tuple.')

Output

watermelon not in the tuple.

Conclusion

In this Python Tutorial, we learned the syntax of tuple.index() method, and how to use it in different scenarios in your Python programs where we need to find the index of specified element in the given tuple.