# iterating in reverse

Greg Chapman glc at well.com
Sat Jan 18 17:25:26 CET 2003

```On 16 Jan 2003 15:46:32 -0800, jbperez808 at yahoo.com (Jonathan P.) wrote:

>First of all, many thanks to all the people in the list
>who have taken the time to respond to my earlier
>questions with excellent answers. Now on to the
>problem at hand...
>
>A list's contents are ordered such that:
>
>>>> x=[1,2,3,4,5]
>
>>>> for i in x:
>      print i
>
>will always print x's contents in the
>same sequence.  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())?

How about something like this (in 2.3):

def seqiter(seq, *args):
'''seqiter(seq, [[start], stop, [step]]) -> seq item iterator'''
if not args:
xr = xrange(len(seq))
else:
slc = slice(*args)
xr = xrange(*slc.indices(len(seq)))
for index in xr:
yield seq[index]

for i in seqiter(x, None, None, -1):
print i

The above avoids constructing a new list, but it might not be too efficient (I'd
guess that for most lists, it would be better to iterate over the slice,
e.g. x[::-1]).  Perhaps the list object should grow a new method taking
([start], stop, [step]) parameters and returning an iterator which produces the
items in the desired order.

---
Greg Chapman

```