I like both wim's and Ignacio's answers. However, I think itertools
provides a slightly more readable alternative, lambda notwithstanding. (For Python 3; for Python 2, use xrange
instead of range
).
>>> from itertools import dropwhile
>>> l = list('apples')
>>> l.index('p')
1
>>> next(dropwhile(lambda x: l[x] != 'p', reversed(range(len(l)))))
2
This will raise a StopIteration
exception if the item isn't found; you could catch that and raise a ValueError
instead, to make this behave just like index
.
Defined as a function, avoiding the lambda
shortcut:
def rindex(lst, item):
def index_ne(x):
return lst[x] != item
try:
return next(dropwhile(index_ne, reversed(range(len(lst)))))
except StopIteration:
raise ValueError("rindex(lst, item): item not in list")
It works for non-chars too. Tested:
>>> rindex(['apples', 'oranges', 'bananas', 'apples'], 'apples')
3