Python List index() Method



The Python List index() method is used to retrieve the lowest index in a list at which a specified object appears. The object can be anything; a single element or a collection of elements in the form of another list, tuple, set etc.

The method also accepts two optional parameters to limit the search range in a list. These two parameters define where the search starts and ends; basically working like a slice notation in Python. The lowest index returned in this case will be relative to the starting index rather than the zeroth index of the list.

Syntax

Following is the syntax for the Python List index() method −

list.index(obj[, start[, end]])

Parameters

  • obj − This is the object to be find out.

  • start − (Optional) The start index where the search starts.

  • end − (Optional) The end index where the search ends.

Return Value

This method returns the first index in the list at which the object is found. If the object is not found in the list, a ValueError is raised.

Example

The following example shows the usage of the Python List index() method.

aList = [123, 'xyz', 'zara', 'abc'];
print("Index for xyz : ", aList.index( 'xyz' )) 
print("Index for zara : ", aList.index( 'zara' ))

When we run above program, it produces following result −

Index for xyz :  1
Index for zara :  2

Example

Now, if we also pass some values as the optional parameters start and end, the method limits the search within these indices.

listdemo = [123, 'a', 'b', 'c', 'd', 'e', 'a', 'g', 'h']
ind = listdemo.index('a', 3, 7)
print("Lowest index at which 'a' is found is: ", ind)

If we compile and run the program above, the output is achieved as follows −

Lowest index at which 'a' is found is:  6

Example

This, however, might raise a question that if a value is present in the list, but not within the search range, what will be the return value? Let us see the example for this scenario below.

listdemo = ['a', 'b', 'c', 'd', 'e', 'g', 'h', 'i']

# The value 'a' is not present within the search range of the list
ind = listdemo.index('a', 2, 5)

# Print the result
print("Lowest index at which 'a' is found is: ", ind)

Executing the program above will raise a ValueError as the value is not present in the given search range.

Traceback (most recent call last):
  File "main.py", line 4, in 
    ind = listdemo.index('a', 2, 5)
ValueError: 'a' is not in list

Example

A ValueError is commonly also raised when the value does not exist in the list. This does not require passing the optional arguments.

listdemo = ['b', 'c', 'd', 'e', 'g', 'h', 'i']

# The value 'a' is not present within the list
ind = listdemo.index('a')

# Print the result
print("Lowest index at which 'a' is found is: ", ind)

On compiling the program above, the output is obtained as follows −

Traceback (most recent call last):
  File "main.py", line 4, in 
    ind = listdemo.index('a')
ValueError: 'a' is not in list
python_lists.htm
Advertisements