Python List index() method
Python List index() method
The list.index () method in Python returns the position at the first occurrence of the specified value.
Syntax
list.index(x[, start[, end]])
Parameter
element – This parameter represents the element whose lowest index will be returned.
start (Optional) – It signifies the position from where the search begins.
end (Optional) – This parameter signifies the position from where the search ends.
Return
This function returns a zero-based index in the list of the first item whose value is equal to x or raises a ValueError if there is no such item.
Example 1
# Python program for demonstration # of list.index() method num_list = [11, 12, 13, 14, 11, 11, 11, 14, 15] # printing the index of '4' in num_list print("The index of value 14:",num_list.index(14)) month_list = ['January', 'Febuary', 'March', 'April', 'May','June'] # printing the index of 'March' in list2 print("The index value of string value March: ",month_list.index('March'))
Output
The index of value 14: 3 The index value of string value March: 2
Example 2
# Python program for demonstration # of list.index() method num_list = [11, 12, 13, 14, 11, 11, 11, 14, 15] # printing the index of '4' in num_list print("The index of value 14:",num_list.index(14)) month_list = ['January', 'Febuary', 'March', 'April', 'May','June'] # printing the index of 'July' in list2, will raise a ValueError as there is no such item. print("The index value of string value July: ",month_list.index('July'))
Output
The index of value 14: 3 Traceback (most recent call last): File "main.py", line 12, in <module> print("The index value of string value July: ",month_list.index('July')) ValueError: 'July' is not in list