Skip to main content

index()

The index() method is a built-in function in Python that returns the index of a specified element in a tuple. It searches for the specified element starting from the beginning of the tuple and returns the index of the first occurrence of the element. If the element is not found, it raises a ValueError.

Parameter Values

Parameter Description
value

The value to search for in the tuple.

start

The index at which to start the search.

stop

The index at which to end the search.

Return Values

The index() method returns an int which is the index of the first occurrence of the value.

How to Use index() in Python

Example 1:

The index() method returns the index of the specified element in a tuple.

tuple1 = (10, 20, 30, 40, 50)
print(tuple1.index(30))
Example 2:

If the element is not found in the tuple, a ValueError is raised.

tuple2 = ('a', 'b', 'c')
try:
    print(tuple2.index('d'))
except ValueError as e:
    print('Element not found in the tuple')
Example 3:

The index() method can also take optional arguments to specify the start and end index for the search.

tuple3 = (7, 8, 9, 8, 10)
print(tuple3.index(8, 1, 4) # Output: 1

Tuple Methods