iterating in reverse
Jonathan P.
jbperez808 at yahoo.com
Fri Jan 17 04:05:31 EST 2003
Erik Max Francis <max at alcyone.com> wrote in message news:<3E274D34.8F0C4348 at alcyone.com>...
> "Jonathan P." wrote:
>
> > Is there an elegant and
> > efficient way to iterate through x in
> > reverse without having to create a reversed
> > copy of it (i.e. y=x[:]; y.reverse())?
>
> It's not too elegant, but
>
> for j in range(len(x) - 1, -1, -1):
> i = x[j]
> print i
This looks like the best bet so far short of using 2.3.
One thing though, would using xrange instead of range
be preferable?
Chad Netzer wrote:
> Yeah, so you may need to do a copy/reverse or a
> reverse/reverse, to keep the original list.
reverse/reverse saves on memory but it implies that
for reverse() to be a win over a reverse iterator it
has to be at least twice as fast as the latter. I
find it very un-Pythonic to have to maintain 2 copies
of the same list just to be able to access it in 2
different ways. reverse/reverse feels pretty unPythonic
as well...
More information about the Python-list
mailing list