How to find the index of an object available in a list in Python?



If you only want the first index of the object, you can simply use the index method on the list. It accepts the object whose position you require. Note that if element is not found in the list, this will throw an error that needs to be handled using try .. expect.  

example

my_list = [2, 1, 3, 8, 5]
print(my_list.index(3))

Output

This will give the output −

2

If you want to print all occurrences of the object, you should use enumerate instead.

example

my_list = [2, 3, 1, -4, -1, -4]
elem = -4
print([i for i, j in enumerate(my_list) if j == elem])

Output

This will give the output −

[3, 5]
raja
Published on 05-Jan-2018 14:33:55
Advertisements