AppDividend
Latest Code Tutorials

Python List Index Example | List index() Function Tutorial

0

Python list index() is an inbuilt function that searches an element in the list and returns its index. The list index() method returns the index of the element in the list. If any element which is not present is searched, then it returns the ValueError. The method index() returns the lowest index in the list that item appears.

Python List Index Example

The syntax for the index() method is the following.

list.index(element)

The element parameter is required, and it is the item that is searched for in the list.

Let us take an example.

# app.py

GoT = ['Daenerys', 'Jon', 'Tyrion']
elementIndex = GoT.index('Jon')
print(elementIndex)

So, the index() method returns an index, and in the above example, it returns Jon’s index which is 1.

Python List Index Example | index() Method Tutorial

Find Index of Item Which Doesn’t Exist

If we find an index of an element that is not present in the list, then it will return a ValueError. Let us see the following code.

# app.py

GoT = ['Daenerys', 'Jon', 'Tyrion']
elementIndex = GoT.index('Arya')
print(elementIndex)

See the output.

Find Index of Item Which Doesn't Exist in Python

Find an index of tuple and list inside a list

Let us find an index of a tuple in the list. Let us look at the following example.

# app.py

GoT2 = ['Daenerys', 'Jon', ('Briane', 'Tormund') , 'Tyrion']
elementIndex2 = GoT2.index(('Briane', 'Tormund'))
print(elementIndex2)

See the output.

Find an index of tuple and list inside a list

So, it works the same as a single element in the list because it behaves as a single element in a list.

Finally, Python List Index Example | index() Method Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.