In this tutorial, we will see about Python List‘s index method.Python List index method is used to find index of element in the list
Python List index example
You can simply use index method to find index of the element in the list. If there are multiple occurences of element, then it will return first element.
Let’s understand this with the help of simple example.
1 2 3 4 |
list1=[1,2,'three','four',5] print("Index of 'three' in list1:",list1.index('three')) |
Output:
If element is not present in the list, then it will raise ValueError.
1 2 3 4 5 |
list1=[1,2,'three','four',5] print("Index of 6 in list1:",list1.index(6)) |
Output:
ValueError Traceback (most recent call last)
1 list1=[1,2,’three’,’four’,5] 2
—-> 3 print(“Index of 6 in list1:”,list1.index(6))
ValueError: 6 is not in list
If there of multiple occurrences of element in the list, then it will return the index of first occurrence of the element.
Output:
If element is not present in the list, then it will raise ValueError.
1 2 3 4 5 |
list1=[1,2,3,2,1] print("Index of 1 in list1:",list1.index(1)) print("Index of 2 in list1:",list1.index(2)) |
Output:
Index of 2 in list1: 1
That’s all about Python List index method.