In Python, you can find the index of an item in a list using the index() method. The index() method returns the first index at which a given element appears in the list.
Here’s an example -
my_list = [10, 20, 30, 40, 50]
#Find the index of the element 30
index_of_30 = my_list.index(30)
print("Index of 30:", index_of_30)
#Find the index of the element 40
index_of_40 = my_list.index(40)
print("Index of 40:", index_of_40)
Output:
Index of 30: 2
Index of 40: 3
However, the index() method raises a ValueError if the element is not in the list. In that case, use a conditional statement or the in operator.
my_list = [10, 20, 30, 40, 50]
element_to_find = 30
if element_to_find in my_list:
index_of_element = my_list.index(element_to_find)
print(f"Index of {element_to_find}: {index_of_element}")
else:
print(f"{element_to_find} not found in the list.")
For more details, visit our Python blogs.