Pre-PEP: reverse iteration methods

Peter Otten __peter__ at
Wed Sep 24 13:00:00 CEST 2003

Raymond Hettinger wrote:

> If you want the indices to match their original position, then you
> would need something like:
>   >>> list(enumerate(mystr).iter_backwards())
>  [(2, 'c'), (1, 'b'), (0, 'a')]
> The implementation would need to access both mystr.iterbackwards()
> and mystr.__len__().
> At first glance, this is a can of worms, a pandora's box,
> a gordian knot, or some unnamed code smell unsuitable
> for this mixed metaphor.

You can count down starting at -1 for reverse enumeration and keep that can
of pandora's knots closed :-)

The only drawback I see would be that the following behaviour might not be
what you expect:

>>> [(i, c, "uvwxyz"[i]) for i, c in reverse_enumerate("abc")]
[(-1, 'c', 'z'), (-2, 'b', 'y'), (-3, 'a', 'x')]


More information about the Python-list mailing list