Re: obtaining the reversal of a sequence?

Guido.van.Rossum@cwi.nl
Fri, 29 Oct 1993 11:43:16 +0100

If speed is what you need, and you need to traverse a list backwards,
there is no way (without resorting to C) to beat

list.reverse()
try:
for item in list: ...
finally:
list.reverse()

A close second which leaves the forward value of list accessible is

rev = list[:]
rev.reverse()
for item in rev: ...

Anything that involves maintaining the loop index in a Python variable
is much slower. I personally wouldn't worry about the space overhead
of the second solution, but some people might. My feeling is that by
the time you have a list that's so long that a second copy of the
*list* (not its items!) is a problem, *doing* anything with all of its
items in a for loop will take forever -- unless you have a totally
memory starved machine with a race horse of a CPU...

> Also note to Terrence Brannon and others who have complained about
> strings being non-mutable: you can probably tell from these various
> pseudo-sequences that it would be pretty easy to make a mutable-string
> class. It isn't something I've felt as a requirement, but since it's
> so easy, maybe we ought to put one in the standard library.

There is already something like this: the built-in array module (which
is currently optional but should be part of every Python interpreter
nevertheless). array.array('c') creates an empty array of characters
which supports list-like operations (including append & insert). The
only drawback is that array objects aren't acceptable to built-in
functions requiring a string, and e.g. file.read() doesn't return an
array so you would have to copy it (e.g. using array.array('c',
file.read()).

--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>