What is index() in Python?

index() is a list method in Python that returns the index of a specified element in a list.

Syntax

The syntax of this function is as follows.


listName.index(element, start, end)

Parameters

The index() method takes one mandatory and two optional parameters:

  1. element: A mandatory argument that specifies the element whose index is required.

  2. start: An optional parameter that sets the starting index for an element search in a list.

  3. end: An optional parameter that specifies the point until which the search needs to be done.

Return value

The return value of the index() function is of two types:

  1. Integer: Tells the index of the specified element.

  2. Value error: If an element is not found in a list, the function returns a value error.

Code

Example 1

In the code below, the index() method returns the index of element d from the list in the form of an integer.

The index of i is a value error because i is not present in the alpha list.

Here, only one necessary parameter is passed into the function to determine the position of the element.

# alpha
alpha = ['a', 'b', 'c', 'd', 'e']
# index of 'd' in alpha
indexOfD = alpha.index('d')
print('The index of d:', indexOfD)
# finding index of a non-existent element in the list
indexNotPresent = alpha.index('i')
# output: vlaue error
print('The index of i:', indexNotPresent)

Example 2

We can also find an element’s index by specifying the starting and ending points for the search in a list with the index() method.

We get a value error by setting the start and end index of a non-existent element.

# alpha
alpha = ['a', 'b', 'c', 'd', 'e', 'f']
# index of 'c' in alpha
# by specifying the start and end index
indexOfC = alpha.index('c', 1, 4)
print('The index of c:', indexOfC)
# finding index of a non-existent element in the list
# by soecifying the start and end index
indexNotPresent = alpha.index('i', 2, 5)
# output: vlaue error
print('The index of i:', indexNotPresent)