Skip to main content

index()

The index() method in Python is a function specific to lists that returns the index of the first occurrence of a specified element in the list. If the element is not found, it will raise a ValueError. The syntax for using the index() method is list_name.index(element).

Parameter Values

Parameter Description
value

The value to search for in the list.

start

The index in the list at which to start the search.

stop

The index in the list at which to end the search.

Return Values

The index() method returns an int representing the index of the first matching item.

How to Use index() in Python

Example 1:

The index() method returns the index of the first occurrence of the specified element in the list.

my_list = [10, 20, 30, 40, 20]
index = my_list.index(20)
print(index)
Example 2:

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

my_list = [10, 20, 30, 40]
try:
    index = my_list.index(50)
    print(index)
except ValueError as e:
    print('Element not found in the list')