iterating in reverse

Chad Netzer cnetzer at
Fri Jan 17 01:56:43 CET 2003

On Thursday 16 January 2003 15:46, 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())?

In Python 2.2.2, you can create a reverse iterator (it may even be 
included.. anyone?).  See my simple implementation below.

FWIW. list.reverse() is often not too bad since it only has to do the 
work of reversing the list indices in memory, not copying the actual 
objects themselves.  Iterating backwards does save an O(N) operation, 
but for small lists, list.reverse() is likely faster.

from __future__ import generators

def reverse_iter( seq ):
    i = 0
    n = len( seq )
    while i < n:
        j = -(i + 1)
        yield seq[ j ]
        i += 1

for c in reverse_iter( 'abcdefg' ):
    print c,

Bay Area Python Interest Group -

Chad Netzer

More information about the Python-list mailing list