Instead of reversing the list, which may be a lengthy operation (l.reverse()
) because it reverses the whole list, I'd simply use a reversed iterator reversed(l)
with whatever matching method you want, since you can stop early at the first match, it may save you time vs reversing the whole list.
Of course there's best case and worst cases for both methods, below may give you an idea, based on where the match is in the list (e.g. towards the end, the beginning, or the middle)
In [1]: l = range(0, 100000)
In [2]: %timeit next((i for i in reversed(l) if i == 1), None)
100 loops, best of 3: 2.94 ms per loop
In [3]: %timeit next((i for i in reversed(l) if i == 50000), None)
1000 loops, best of 3: 1.39 ms per loop
In [4]: %timeit next((i for i in reversed(l) if i == 99000), None)
10000 loops, best of 3: 29.4 µs per loop
Below is an idea of how long it takes to reverse the same list:
In [5]: %timeit l.reverse()
10000 loops, best of 3: 71.5 µs per loop
Note: I ran above on Python 2, so range()
is a list not an iterator, so no need to list(range())
it to make the comparison worthwhile.