Python List index() - Get Index of Element
The index()
method returns the index position of the first occurance of the specified item. Raises a ValueError if there is no item found.
Syntax:
list.index(element, start, end)
Parameters:
- element: (Required) The element whose index needs to be searched.
- start: (Optional) The index position to start searching from.
- end: (Optional) The ending index position to stop searching.
Return Value:
An integer value indicating zero based index position of the element in the list.
The following example demonstrates the index()
method.
cities = ['Mumbai', 'London', 'Paris', 'New York','Delhi','Chennai','Paris']
pos = cities.index('Paris')
print("First occurances of 'Paris' is at: ", position)
next_pos = cities.index('Paris', pos + 1) # searches next position of 'Paris'
print("Next occurances of 'Paris' is at: ", next_pos)
First occurances of 'Paris' is at: 2
Next occurances of 'Paris' is at: 6
It throws an error if the specified element is not found in the list.
cities = ['Mumbai', 'London', 'Paris', 'New York','Delhi','Chennai']
pos = cities.index('Bangalore')
print('The index of Paris is: ', pos)
Traceback (most recent call last):
pos = cities.index('Bangalore')
ValueError: 'Bangalore' is not in list
The index()
method can also take the starting and ending indices as arguements to search in a particular section of the list.
numbers = [1, 5, 3, 4, 5, 6, 3, 5, 9, 6]
pos = numbers.index(5) # starts from 0 till end
print("The index of 5: ", position)
pos = numbers.index(5, 2, 5) # starts from 2nd index till 4th index
print("The index of 5 from 2nd index: ", position)
pos = numbers.index(5, 5) # starts from 5th index till end
print("The index of 5 from 5th index: ", position)
pos = numbers.index(5, 8) # throws ValueError
The index of 5: 1
The index of 5 from 2nd index: 4
The index of 5 from 5th index: 7
ValueError: 5 is not in list
In the above example, numbers.index(5, 8)
throws an error because the index method starts searching from 8th position after which 5 not found.