What is the best way to loop over a python string backwards?
The following seems a little awkward for all the need of -1 offset:
string = \"trick or
Less code is usually faster in Python. Luckily, you don't have to guess:
python -mtimeit -s"s='x'*100000" "for x in s[::-1]: pass"
100 loops, best of 3: 1.99 msec per loop
python -mtimeit -s"s='x'*100000" "for x in reversed(s): pass"
1000 loops, best of 3: 1.97 msec per loop
python -mtimeit -s"s='x'*100000" "for i in xrange(len(s)-1, 0-1, -1): s[i]"
100 loops, best of 3: 4.95 msec per loop
So the shorter code is a bit faster, but it comes with a memory overhead.