Pre-PEP: reverse iteration methods

Raymond Hettinger vze4rx4y at
Wed Sep 24 11:57:18 CEST 2003

[Raymond Hettinger]
> >    for elem in seqn.iter_backwards():
> >        print elem

[Stephen Horne]
> That is a pretty long name. Can we use the convention from itertools
> where an 'i' prefix is sufficient to suggest an iterator, giving
> 'ibackwards' or 'ireverse' or similar.

That sounds reasonable to me.  I'll add that alternative to the PEP.

If the discussion on enumerate() is any indication, then the naming
discussion will be much more lively than on the idea itself.  Perhaps,
Alex will once again be able to suggest a musically perfect, beautiful
Italian name.

BTW, if you think iter_backwards is long, then take a look at some
of the method names in the sets module.

> Second, I'm not quite ready to drop my property idea ;-)
> An advantage is that the object returned by the property can sensibly
> support more than just iteration - e.g. slicing (as touched on in the
> PEP284 thread). So for instance...
> >>> x = range(10)
> >>> list(x.backward)
> [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

I'm not clear on the details of what you're proposing.  What is
Please show what a pure python version would look like
(taking UserList as an example).

> >* Should file objects be included?  Implementing reverse iteration may not
> >  be easy though it would be useful on occasion.
> IMO no - doing this essentially needs the whole file to be read into
> memory, in which case you may as well read the whole file into a list
> and then iterate the list backwards.

Oh, it could be done using seeks and whatnot;
however, the code might be grotesque.

> >* Should enumerate() be included?  It would only provide reverse iteration
> >  whenever the underlying sequence supported it.
> Why not...
>   for i, j in enumerate (listname.iter_backwards ()) :
> in other words, as enumerate can handle the already-reversed
> sequence/iteration, I don't see the point.

The point is that enumerate will starting numbering from zero
for the last item:

   >>> mystr = 'abc'
   >>> list(enumerate(mystr.iter_backwards()))
   [(0, 'c'), (1, 'b'), (2, 'a')]

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.

Raymond Hettinger

More information about the Python-list mailing list