Home »
Python
Python List index() Method with Example
Python List index() Method: Here, we are going to learn how to find the index of the given element in a list?
Submitted by IncludeHelp, on December 03, 2019
List index() Method
index() method is used to get the index of the specified element, the method is called with this list and element can be supplied as an argument, it returns the index of the first occurrence of the element in the list.
Syntax:
list_name.index(element)
Parameter(s):
- element – It represents an element whose index to be found.
Return value:
The return type of this method is <class 'int'>, it returns an integer element that will the index of the first occurrence of the element, or it returns a ValueError if element does not exist in the list.
Example 1:
# Python List index() Method with Example
# declaring the list
cars = ["Porsche", "Audi", "Lexus", "Porsche", "Audi"]
# printing the list
print("cars: ", cars)
# finding index of "Porsche"
pos = cars.index("Porsche")
print("Porsche's index is:", pos)
# finding index of "Lexus"
pos = cars.index("Lexus")
print("Lexus's index is:", pos)
Output
cars: ['Porsche', 'Audi', 'Lexus', 'Porsche', 'Audi']
Porsche's index is: 0
Lexus's index is: 2
Example 2:
# Python List index() Method with Example
# declaring the lists
x = ["ABC", "XYZ", "PQR","ABC", "XYZ", "PQR"]
y = ["PQR", "MNO", "YXZ", "YXZ"]
z = ["123", "456", "789"]
# printing the findex of given element
print('x.index("ABC"):', x.index("ABC"))
print('y.index("YXZ"):', y.index("YXZ"))
print('z.index("789"):', z.index("789"))
# ValueError
print('x.index("MNO"):', x.index("MNO"))
Output
x.index("ABC"): 0
y.index("YXZ"): 2
z.index("789"): 2
Traceback (most recent call last):
File "main.py", line 14, in <module>
print('x.index("MNO"):', x.index("MNO"))
ValueError: 'MNO' is not in list
TOP Interview Coding Problems/Challenges