Python lists have the index()
method, which you can use to find the position of the first occurrence of an item in a list. Note that list.index()
raises ValueError
when the item is not present in the list, so you may need to wrap it in try
/except
:
try:
idx = lst.index(value)
except ValueError:
idx = None
To find the position of the last occurrence of an item in a list efficiently (i.e. without creating a reversed intermediate list) you can use this function:
def rindex(lst, value):
for i, v in enumerate(reversed(lst)):
if v == value:
return len(lst) - i - 1 # return the index in the original list
return None
print(rindex([1, 2, 3], 3)) # 2
print(rindex([3, 2, 1, 3], 3)) # 3
print(rindex([3, 2, 1, 3], 4)) # None