Pre-PEP: reverse iteration methods

Raymond Hettinger vze4rx4y at verizon.net
Wed Sep 24 02:30:31 CEST 2003


Here is a discussion draft of a potential PEP.
The ideas grew out of the discussion on pep-284.
Comments are invited.  Dart throwing is optional.


Raymond Hettinger

-------------------------------------------------------------

PEP: 323
Title: Add Reverse Iteration Methods
Version: $Revision: 1.1 $
Last-Modified: $Date: 2003/03/11 04:49:44 $
Author: Raymond Hettinger <python at rcn.com>
Status: Draft
Type: Standards Track
Content-Type: text/x-rst
Created: 23-Sep-2003
Python-Version: 2.4
Post-History: 23-Sep-2003


Abstract
========

This proposal is to extend the API of several sequence types
to include methods for iterating over the sequence in reverse.


Motivation
==========

For indexable objects, current methods for reverse iteration are
error prone, unnatural, and not especially readable::

    for i in xrange(n-1, -1, -1):
        print seqn[i]

One other current approach involves reversing a list before iterating
over it.  That technique wastes computer cycles, memory, and lines of
code.  Also, it only works with lists (strings, for example, do not define
a reverse method)::

    rseqn = list(seqn)
    rseqn.reverse()
    for elem in rseqn:
        print elem

Reverse iteration is much less common than forward iteration, but it
does arise regularly in practice.


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

The new protocol would be applied to lists, strings, xranges objects,
and possibly other sequence objects as well (depending on use cases
and implementation issues).  It would not apply to unordered collections
like dicts and sets.

No language syntax changes are needed.


Open Issues
===========

* Should tuples be included?  In the past they have been denied some list
  like behaviors such as count() and index().

* Should file objects be included?  Implementing reverse iteration may not
  be easy though it would be useful on occasion.

* Should enumerate() be included?  It would only provide reverse iteration
  whenever the underlying sequence supported it.


Copyright
=========

This document has been placed in the public domain.







More information about the Python-list mailing list