Python: list.index()

Python Tutorials

Summary: In this tutorial, we will learn to find the index of an item in a list using the Python list.index() method.

The list.index(x) method in Python returns the index of the specified item (x) in the current list object.

For example, in the following Python code, the index method returns the index value of ‘Python’:

>>> l = ['C++', 'Java', 'Python']
>>> l.index('Python')
2

Parameters and Return Value

The list.index(x[, start[, end]]) method accepts three positional arguments:

ParameterTypeDescription
xrequiredAn element whose index needs to be returned.
startoptionalIndex value to set the starting point of the search limit.
endoptionalIndex value to set the end-point of the search limit.

It returns the index value of the specified item(i.e., x) if it is present in the list otherwise it throws the ValueError.

Examples using list.index()

Example 1: Search index of an item that is present in the list:

>>> l = ['Tokyo', 'Berlin', 'Oslo', 'Rio']
>>> l.index('Berlin')
1

Example 2: Search index of an item that is not present in the list:

>>> l = ['Tokyo', 'Berlin', 'Oslo', 'Rio']
>>> l.index('Moscow')
ValueError: 'Moscow' is not in list

Because the index method on list throws an error when the specified item is not present, we should wrap its usage with try & except.

>>> try:
...     l = ['Tokyo', 'Berlin', 'Oslo', 'Rio']
...     print(l.index('Moscow'))
... except(ValueError):
...     print('Item not present')
... 
Item not present

Conclusion

The list.index() method of the list returns the index value of the specified item if it is present in the list otherwise it throws the ValueError.

Leave a Reply

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