iters on ints? (reducing the need for range/xrange)

Michael Robin me at mikerobin.com
Fri Nov 9 11:51:05 EST 2001


There's a subtle off-by-one bug lurking for
beginners if this syntax is allowed.
Usually for loops are inclusive to the ranges
given, so it would be tempting to write:
>>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> # this works, or gives "list index out of range"
>>> for i in len(lst): print lst[i] 
  or
>>> # this works, or really calls the fn eleven times
>>> for i in 10: doSomethingTenTimes()

Only one of these can work - the above
are either equivalent to the interval [0..9]
or [0..10] - assuming it's understood that the
start is 0 and not 1. Using (x)range makes it explicit
that we're talking about [0..n-1], i.e., [0..n).
(Well, it doesn't really make that explicit at 
all - what it makes explicit is that 
range(len(s))  will "just work" for whatever 
sequence is given.)

I'd like to see (x)range take a sequence, as in:
>>> for i in range(lst): print lst[i]
which seems like a natural thing for range to do -
polmorphic and pythonic.
(At lot more natural than an implicit conversion
from an integral type to a sequence.)
I think this has been discussed before.

mike

James_Althoff at i2.com wrote in message news:<mailman.1005262511.32243.python-list at python.org>...
> [jim]
> for i in 10:
>     doSomething(i)
> 
> [Rainer and Emile]
> I like it.
> Sounds good.
> 
> [Steve]
> If "for i in 10:" was legal, I'ld guess it meant the same thing as
> "for i in [10]:" or "for i in (10,):"
> 
> A file *IS* a sequence -- although you could just as easily slice it
> by characters as lines -- or by any arbitrary object for binary files,
> as Pascal does. If the integer 10 suggests any sort of sequence, it's
> the singleton sequence containing: 10.
> 
> [jim]
> On the other hand, 2.2 takes us away from the concept of "suggesting a
> sequence" in the context of for-loops.  Instead, the new for-loops are
> *iterator*-protocol based (not *sequence*-protocol based).  They iterate
> over something that *is* or *can return* an iterator object.
> 
> So under the proposed scenario, if one looks at 10 and asks "if 10 were to
> return an iterator, what would that iterator iterate over?", then it seems
> that range(10) would be a more *useful* answer than a sequence of one
> element 10.
> 
> Jim



More information about the Python-list mailing list