How to locate the position of an element in a list using Python?
In Python, the index() method can be used to locate the position of an element in a list. It returns the index value of the element’s first occurrence.
Example code:
my_list = [1, 2, 3, 4, 5]
element = 3
index = my_list.index(element)
print(index)
Output result:
2
If the element being searched for is not in the list, the index() method will raise a ValueError exception. To avoid this exception, you can use the in keyword for checking.
Example code:
my_list = [1, 2, 3, 4, 5]
element = 6
if element in my_list:
index = my_list.index(element)
print(index)
else:
print("Element not found")
Output result:
Element not found
Please note that the index() method only returns the index of the first occurrence of an element. If you want to find all occurrences, you can use list comprehension or loop through the list.