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
reversed
takes an iterable and and returns an iterator that moves backwards. string[::-1]
is fine, but it creates a new, reversed string instead. If you just want to iterate, then this will probably better:
for c in reversed(string):
print c
If you want to use the reversed string afterwards, creating it once will be better.
Yes, the second syntax shortcut creates an intermediate string and has an associated performance penalty.
The first version is better written as:
for index, char in enumerate(reversed(s)):
print "pos %d: %s" % (index, char)
Which is easy to comprehend. Neither reversed nor enumerate` need to make a copy of the string.
Also be careful about using string
as a variable name, as it is also the name of a module in the standard library.
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.
Python 3 with enumerate
and reversed
methods:
string = "trick or treat"
for i, c in enumerate(reversed(string)):
print(i, c)
You can use print(c) just for retrieving each character without the index.
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.