Best way to loop over a python string backwards

clwen picture clwen · Nov 1, 2011 · Viewed 90.1k times · Source

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 treat"
for i in range(len(string)-1, 0-1, -1):
    print string[i]

The following seems more succinct, but is it actually generate a reversed string so that there is a minor performance penalty?

string = "trick or treat"
for c in string[::-1]:
    print c

Answer

Raymond Hettinger picture Raymond Hettinger · Nov 1, 2011

Try the reversed builtin:

for c in reversed(string):
     print c

The reversed() call will make an iterator rather than copying the entire string.

PEP 322 details the motivation for reversed() and its advantages over other approaches.