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
Is there any significant difference in term of speed other than potential overheads if we have to enclose
s.index()within atry/except.
In (C)Python at least, find, index, rfind, rindex are all wrappers around an internal function any_find_slice.
The implementation is the same. The only difference is that index and rindex will raise a ValueError for you if it finds that the result of calling any_find_slice is -1.
If you went ahead and timed these you'd see how there's clearly no meaningful difference between them:
โ ~ python -m perf timeit -s "s = 'a' * 1000 + 'b'" "s.find('b')"
Median +- std dev: 399 ns +- 7 ns
โ ~ python -m perf timeit -s "s = 'a' * 1000 + 'b'" "s.index('b')"
Median +- std dev: 396 ns +- 3 ns
I'm using perf for the timings here.
I'm guessing in other implementations of Python this shouldn't differ. Both methods do the same thing and differ only in how they react when the requested element was not found.
@Dimitris's answer showed that s.find() and s.index() perform equally well if the substring is found.
But as @augustomen pointed out, if the substring is not found then s.index() will be significantly slower due to the exception handling. We can test this with the following code snippets.
Note that I'm using a different machine to @Dimitris so my timings cannot be compared with his.
$ python3 -m timeit -s "s = 'a' * 1000" "s.find('b')"
5000000 loops, best of 5: 87.3 nsec per loop
$ python3 -m timeit -s "s = 'a' * 1000" "try: s.index('b')" "except ValueError: pass"
1000000 loops, best of 5: 242 nsec per loop
It's clear that s.find() is the winner when the substring is not found, but is that just because we didn't include a try/except block for it?
Let's try adding a try/except block to s.find() (even though we know it won't be triggered).
$ python3 -m timeit -s "s = 'a' * 1000" "try: s.find('b')" "except ValueError: pass"
5000000 loops, best of 5: 89.1 nsec per loop
We see here that the mere presence of a try/except block barely alters the time at all. It's only when the exception is actually triggered that we incur a meaningful hit to performance.
The moral of the story is to use s.find() if there's a reasonable chance that the substring won't be found.
If you're sure that the substring will almost always be found then you can use either s.find() or s.index(). You might prefer s.index() in that case, because the try/except syntax signals to other developers that you are handling an edge case that you don't expect will occur very often.