The index Method in Python: Finding the Index of an Element in a List
Returns the smallest index where an element is found in a list.
index(x[, start[, end]])
x-- element whose index must be determinedstart=0-- starting index of the slice in the list where the element must be foundend=None-- ending index of the slice in the list where the element must be found
If the element is not found, a ValueError is raised.
my_list = ['eggs', 'spam', 'bar']
my_list.index('spam') # 1
my_list.index('baz') # ValueError: 'baz' is not in list
my_list.index('spam', 2) # ValueError: 'spam' is not in list
The optional parameters start and end can take any values supported by slicing, including negative values.
Use this method only when you need to find the index of an element. For a simple check of element presence, use the in operator:
my_list = ['eggs', 'spam', 'bar']
if 'spam' in my_list: ... # True