Python Tutorial Python Advanced Python References Python Libraries

Python List - index() Method



The Python index() method returns the index number of first occurrence of the specified element in the list. It returns the zero-based index.

The method raises a ValueError, if the specified element is not found.

Syntax

list.index(elem, start, end)

Parameters

elem Required. Specify the value of the element which need to be searched in the list.
start Optional. Specify the starting point of the search in the list.
end Optional. Specify the end point of the search in the list.

Return Value

Returns the index number of first occurrence of the specified element in the list.

Example:

In the example below, index() method is used to find out index number of first occurrence of an element called 'MAR' in the list called MyList

MyList = ['JAN', 'FEB', 'MAR', 'APR', 'MAR']

#first occurrence of 'MAR' in the whole list
x = MyList.index('MAR') 
print("The index of 'MAR' is:", x)

The output of the above code will be:

The index of 'MAR' is: 2

Example:

In this example, index() method is used with optional arguments to find out the index number of first occurrence of 10 in the specified list.

MyList = [10, 20, 30, 40, 50, 10, 70, 80]

#first occurrence of 10 in the whole list
x = MyList.index(10) 
print("The index of 10 is:", x)

#first occurrence of 10 in the specified
#section of the list
y = MyList.index(10, 1, 8) 
print("The index of 10 in index range [1,8) is:", y)

The output of the above code will be:

The index of 10 is: 0
The index of 10 in index range [1,8) is: 5

❮ Python List Methods