How about:
len(a) - a[-1::-1].index("hello") - 1
Edit (put in function as suggested):
def listRightIndex(alist, value):
return len(alist) - alist[-1::-1].index(value) -1
Answer from EwyynTomato on Stack OverflowHow about:
len(a) - a[-1::-1].index("hello") - 1
Edit (put in function as suggested):
def listRightIndex(alist, value):
return len(alist) - alist[-1::-1].index(value) -1
This should work:
for index, item in enumerate(reversed(a)):
if item == "hello":
print len(a) - index - 1
break
If you are actually using just single letters like shown in your example, then str.rindex would work handily. This raises a ValueError if there is no such item, the same error class as list.index would raise. Demo:
>>> li = ["a", "b", "a", "c", "x", "d", "a", "6"]
>>> ''.join(li).rindex('a')
6
For the more general case you could use list.index on the reversed list:
>>> len(li) - 1 - li[::-1].index('a')
6
The slicing here creates a copy of the entire list. That's fine for short lists, but for the case where li is very long, it may be more efficient to use a reverse iteration and avoid the copy:
def list_rindex(li, x):
for i in reversed(range(len(li))):
if li[i] == x:
return i
raise ValueError("{} is not in list".format(x))
One-liner version:
next(i for i in reversed(range(len(li))) if li[i] == 'a')
A one-liner that's like Ignacio's except a little simpler/clearer would be
max(loc for loc, val in enumerate(li) if val == 'a')
It seems very clear and Pythonic to me: you're looking for the highest index that contains a matching value. No nexts, lambdas, reverseds or itertools required.