iterating in reverse
cnetzer at mail.arc.nasa.gov
Fri Jan 17 11:05:47 CET 2003
On Friday 17 January 2003 00:54, Jonathan P. wrote:
> The main thing that bugs me is that I have to choose between
> storing 2 copies of the same data (one reversed, the other not)
> or I have to do a couple of reverse()s each time (to undo the
> transformation) I need to access the list in reverse. The former
> is wasteful of space, the latter of performance.
Although, as Paul Rubin pointed out, even though you may iterate in one
direction at a time, you can access in either order. Rather than
iterating directly over the contents, you iterate over a list of
indices (using range), and you can use the indices to count from the
from or the back.
So, that may really be the best option in these circumstances.
seq = "the quick brown fox jumped over the lazy dog"
for i in xrange( len( seq ) ):
forward_iter = seq[i]
backward_iter = seq[-(i + 1)]
pass # do whatever you need
In this case, you don't copy or generate any new lists at all, so it
should be quite quick.
Bay Area Python Interest Group - http://www.baypiggies.net/
More information about the Python-list