PEP 276 Simple Iterator for ints
David Eppstein
eppstein at ics.uci.edu
Thu Nov 15 14:50:59 EST 2001
In article <3BF40F8A.378CC6F8 at ccvcorp.com>,
Jeff Shannon <jeff at ccvcorp.com> wrote:
> Which is exactly why I think that the Haskell-ish syntax is a bad idea. This
> syntax cries out to be a closed interval, and it would be very confusing if
> used as a half-open interval. But that would make it the *only* case of
> Python using a closed interval. I find that inconsistency to be *far* more
> jarring than the use of range().
I don't buy this argument. Currently AFAIK the *only* cases of Python
using intervals at all are range() and xrange(), which I've argued are
unsatisfactory -- what's the point of changing to something better if you
require it to be consistent with the bad solution currently in place?
Don't tell me it's for consistency with C, either -- in C, closed and open
intervals are equally easy.
Let me see if I can list some likely uses of ranges:
- Loops over the elements of a sequence. Better handled by "for item in
sequence" or, as someone recently suggested, "for index in
indices(sequence)".
- Numbering lines of output. Most commonly done from 1..n instead of from
0..n-1.
- Functional programming e.g. "def factorial(n):
reduce(multiply,range(1,n+1))" vs "reduce(multiply,[1,2,...n])". A closed
interval would be more natural.
- Loops where you want to execute a given number of times but you don't
actually use the index within the loop. "for index in range(n)" and "for
index in [1, 2, ... n]" are equally natural.
- Dynamic programming type algorithms as in the lecture notes I cited
earlier. It's not uncommon to see loops over ranges like [0, 1, 2, ... n],
for instance I think this is the natural way to index the longest common
subsequence dynamic program. It's also not uncommon for some of the loop
indices to run backwards. These are very unnatural to express in half-open
format -- e.g. the interval above is range(0,n+1,1) or shorter range(n+1)
while the backwards one is range(n,-1,-1) -- quick, which -1 is the
increment and which is the end of the interval?
Looking through the Python code I've worked with recently, I found only one
example of range, in code by Thierry Bousch for reading EXIF data:
for i in range(entries):
do something with (ifd + 2 + 12*i)
It seems to me equally straightforward to do this as a 1-based closed
interval:
for i in [1, 2, ... entries]:
do something with (ifd + 12*i - 10)
--
David Eppstein UC Irvine Dept. of Information & Computer Science
eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/
More information about the Python-list
mailing list