Python List index()

Previous
Next

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.

list1=[1,2,'three','four',5] print("Index of 'three' in list1:",list1.index('three'))

Output:

Index of ‘three’ in list1: 2

If element is not present in the list, then it will raise ValueError.

list1=[1,2,'three','four',5] print("Index of 6 in list1:",list1.index(6))

Output:

—————————————————————————
ValueError Traceback (most recent call last)
in ()
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.
[/datacamp_sample_code]
[/datacamp_exercise]
Output:

Index of ‘three’ in list1: 2

If element is not present in the list, then it will raise ValueError.

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 1 in list1: 0
Index of 2 in list1: 1

That’s all about Python List index method.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog