Pre-PEP: reverse iteration methods

Stephen Horne $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk
Wed Sep 24 07:53:09 CEST 2003


On Wed, 24 Sep 2003 00:30:31 GMT, "Raymond Hettinger"
<vze4rx4y at verizon.net> wrote:

>Proposal
>========
>
>Add a method called iter_backwards() to sequence objects that can benefit
>from it.  The above examples then simplify to::
>
>    for i in xrange(n).iter_backwards():
>        print seqn[i]
>
>    for elem in seqn.iter_backwards():
>        print elem

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.

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]
>>> list(x.backward [::2])
[8, 6, 4, 2, 0]

>* 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.

>* 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.


-- 
Steve Horne

steve at ninereeds dot fsnet dot co dot uk




More information about the Python-list mailing list