Pre-PEP: reverse iteration methods
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.
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>
Type: Standards Track
This proposal is to extend the API of several sequence types
to include methods for iterating over the sequence in reverse.
For indexable objects, current methods for reverse iteration are
error prone, unnatural, and not especially readable::
for i in xrange(n-1, -1, -1):
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)
for elem in rseqn:
Reverse iteration is much less common than forward iteration, but it
does arise regularly in practice.
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():
for elem in seqn.iter_backwards():
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.
* 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.
This document has been placed in the public domain.
More information about the Python-list