AppDividend
Latest Code Tutorials

Python List Index Example | index() Method Tutorial

0

Python List Index Example | index() Method Tutorial is today’s topic. Python list index() method 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 index() method is following.

list.index(element)

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

Let us take an example.

# app.py

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

So, 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 which 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)

The output is following.

 

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 following output.

 

Find an index of tuple and list inside a list

So, it works 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.