index() method in Python Lists can be used to find the first occurrence of a given element in the given list.
The index() method by default, returns an integer, denoting the first occurrence of the given element.
Please note that, integer is returned as per 0 based indexing.
Syntax
list.index(item)
item: element whose index is required.
l = [1, 3, 5, 2, 8, 3]
print(l.index(2)) # returns 3
print(l.index(8)) # returns 4
print(l.index(3)) # returns 1 ignoring the further occurrences
O/P
3
4
1
If we try to find the index of the element which does not exists in the given list, then, we get
ValueError : item is not in list
Let’s modify the above code (a bit)
l = [1, 3, 5, 2, 8, 3]
print(l.index(10))
O/P
Traceback (most recent call last):
File “”, line 2, in
ValueError: 10 is not in list
That’s all here.
