Comment on PEP-0322: Reverse Iteration Methods

Stephen Horne $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk
Fri Sep 26 14:23:12 EDT 2003


On Fri, 26 Sep 2003 09:18:18 -0700, David Eppstein
<eppstein at ics.uci.edu> wrote:

>In article <WNYcb.12686$yD1.1505440 at news20.bellglobal.com>,
> "Sean Ross" <sross at connectmail.carleton.ca> wrote:
>
>> How about
>> 
>> from itertools import ireverse
>> for i in ireverse(xrange(n)):
>>     # suite
>> 
>> ireverse(), like imap(), izip(), etc., suggests that the operation is
>> iterative, and that no modification of the original sequence will be
>> performed. Others have suggested riter() (right iteration), in order to form
>> an association with the iter() builtin. As a matter of taste, I prefer
>> ireverse().
>
>ireverse, like imap(), izip(), etc., suggests that the operation happens 
>without the memory overhead of copying the whole sequence into a list 
>before reversing it.  Do you have some plan for how to do that e.g. with 
>simple generators?  Or easy to understand explanation for which things 
>can be ireversed and which can't?

How about this - only support ireverse for sequences (identified using
len, and perhaps with a check for the keys method in case of mapping
types) - not for iterators at all.

Add an xrange_backward function to complement xrange rather than
trying to modify the result of xrange, and where an object can
logically support reverse iteration have a method or property that
returns an alternative generator/iterator.

At its simplest, something like...

class newlist (list) :
  def ibackward (self) :
    i = len(self)
    while i > 0 :
      i -= 1
      yield i

...is no great burden for most built-in sequence types, and would
define a protocol for other types to follow where appropriate. It
doesn't need a big memory overhead.

Rather than define a separate xrange_backwards, it is worth noticing
that the built-in 'functions' xrange and enumerate actually seem to be
classes. We could add factory methods, set up to effectively give
alternate constructors, to allow syntax such as...

  for i in xrange.backward (10) :
    ...

  for i, j in enumerate.backward (seq) :
    ...
    

-- 
Steve Horne

steve at ninereeds dot fsnet dot co dot uk




More information about the Python-list mailing list