Newbie question, Help needed!

Peter Otten __peter__ at web.de
Fri Mar 12 22:36:14 CET 2004


Antti Isomursu wrote:

> Ok, this is my problem.
> I have a list, with several items.
> I can move forward in that list using iterator (for example, iter(x)
>  and then, it.next()...)
> 
> But how can I move backwards?

>>> def reverse(seq):
...     for i in xrange(len(seq)-1, -1, -1):
...             yield seq[i]
...
>>> for c in reverse("abc"): print c
...
c
b
a
>>> r = reverse(range(5))
>>> r.next()
4
>>> r.next()
3

Python 1.4 will have something similar built in.
Or you iterate over a reversed copy:

for item in alist[::-1]:
   # do your stuff

>>> iter(range(5)[::-1]).next()
4

Peter



More information about the Python-list mailing list