Python List index()

Python list‘s index method searches for the element in the list, if element is not present in the list then it will raise ValueError.


Syntax

Here list1 is object of the list and item is the element you want to search in the list.


Return

return index of the item but if item is not present in the list, it will raise ValueError.


Example

Let’s see a very simple example:

list1=['One','two','three','four'] i=list1.index('three') print("Index of three:",i)

Output:

Index of three: 2

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

list1=['One','two','three','four'] i=list1.index('five') print("Index of five:",i)

Output:

—————————————————————————
ValueError Traceback (most recent call last)
in ()
1 list1=[‘One’,’two’,’three’,’four’]
—-> 2 i=list1.index(‘five’)
3 print(“Index of five:”,i)

ValueError: ‘five’ is not in list

Let’s see how to get index of set if it is inside the list.

list1=['One','two',{1,3,4,5},'three','four'] i=list1.index({1,3,4,5}) print("Index of set:",i)

Output:

Index of set: 2

That’s all about Python List index() method.

Leave a Reply

Your email address will not be published. Required fields are marked *