To find the index of a specified element in a list in Python, you can use the index
method of the list class.
In this example,
my_list
with some elements.index
method of the list object my_list
to find the index of a specific element.index
method returns the index of the first occurrence of the element in the list, or raises a ValueError
if the element is not found.my_list = [10, 20, 30, 40, 50]
index = my_list.index(40)
print(f'Index of element is: {index}')
Index of element is: 3
In this example,
my_list
with some string elements.index
method of the list object my_list
to find the index of a specific string.index
method returns the index of the first occurrence of the string in the list, or raises a ValueError
if the string is not found.my_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']
index = my_list.index('cherry')
print(f'Index of element is: {index}')
Index of element is: 2
In this tutorial, we learned How to get the Index of Specified Element in a List in Python language with well detailed examples.