Indentifying the LAST occurrence of an item in a list
bearophileHUGS at lycos.com
bearophileHUGS at lycos.com
Wed Apr 4 15:39:30 EDT 2007
Terry Reedy:
> def rindex(lis, item):
> for i in range(len(lis)-1, -1, -1):
> if item == lis[i]:
> return i
> else:
> raise ValueError("rindex(lis, item): item not in lis")
This is an alternative, I don't know if it's faster:
def rindex(seq, item):
for pos, el in enumerate(reversed(seq)):
if item == el:
return len(seq) - 1 - pos
else:
raise ValueError("rindex(lis, item): item not in lis")
t = [0, 1, 2, 3, 0]
print rindex(t, 0)
print rindex(t, 3)
print rindex(t, 1)
Bye,
bearophile
More information about the Python-list
mailing list