In this article, we will see different ways to get the index of an item in a Python list.
Using index method
The easy and straightforward way is to use the index()
. The index method returns the index of the first occurrence of the item in the list.
Following is the example:
my_list = ['apple', 'banana', 'cherry', 'banana', 'orange']
item = 'banana'
index = my_list.index(item)
print(index)
In the above example, we created a list my_list
with some fruits and then we define an item banana
and use the index()
method to find the index of the first occurrence of the banana
item in the list.
The above program will give 1 as an output because the first occurrence of the banana is present at index 1.
If the item is not found in the list, the index()
method raises a ValueError
. We can use try-except to avoid this error.
my_list = ['apple', 'banana', 'cherry', 'banana', 'orange']
item = 'mango'
try:
index = my_list.index(item)
print(index)
except ValueError:
print(f"{item} not found in the list")
In the above example, we try to find the item’s index in the list. Since the mango
item is not on the list, the ValueError
is caught by the except block and the message “mango not found in the list” is printed.
Using for loop
By using for loop we can find the index of an item in a list. With for loop, we iterate through each item in the list and check if it matches the item that we are looking. If it matches we will return the index.
my_list = ['apple', 'banana', 'cherry', 'banana', 'orange']
item = 'banana'
for i in range(len(my_list)):
if my_list[i] == item:
print(i)
break
In the above example, we define a list my_list
with some fruits. We then define an item banana
. Using for loop we iterate through each item in the list and check if it matches the banana
item. If we find a match, we print the element’s index and then exit the loop using the break statement.