The index method
The index method searches for an element in a list and returns the index of its first occurrence. In the first parameter, we specify the element we are interested in. In the second optional parameter, we specify the search start position, and in the third optional parameter, the search end position.
Syntax
list.index(what are we looking for, [start searching], [end of search])
Example
Let's find the position of the first occurrence of the element 'ab':
lst = ['ab', 'cd', 'ab', 'ef', 'ab']
print(lst.index('ab', 1, 3))
Result of code execution:
0
Example
Now let's set the positions for the start and end of the search:
lst = ['ab', 'cd', 'ab', 'ef', 'ab']
print(lst.index('ab', 1, 3))
Result of code execution:
2
Example
Let's look for the missing element:
lst = ['ab', 'cd', 'ab', 'ef', 'ab']
print(lst.index('xx'))
In this case, the method will return us an error:
ValueError: 'ab' is not in list