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:
-
element: A mandatory argument that specifies the element whoseindexis required. -
start: An optional parameter that sets the startingindexfor an element search in a list. -
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:
-
Integer: Tells theindexof the specified element. -
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.
# alphaalpha = ['a', 'b', 'c', 'd', 'e']# index of 'd' in alphaindexOfD = alpha.index('d')print('The index of d:', indexOfD)# finding index of a non-existent element in the listindexNotPresent = alpha.index('i')# output: vlaue errorprint('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.
# alphaalpha = ['a', 'b', 'c', 'd', 'e', 'f']# index of 'c' in alpha# by specifying the start and end indexindexOfC = 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 indexindexNotPresent = alpha.index('i', 2, 5)# output: vlaue errorprint('The index of i:', indexNotPresent)