number ranges

Tim Hochberg tim.hochberg at ieee.org
Tue Feb 21 17:09:57 EST 2006


[Lots of proposals snipped]

90% of my gripes with range disappeared with the addition of enumerate. 
However, if there's going to be another round of range literal proposals 
I might as well throw out what seems (to me anyway) like the only 
halfway obvious choice in the context of Python.

1. a:b:c is equivalent to slice(a,b,c) with the usual rules that missing 
values are mapped to None: Parentheses would be required where this 
construct would otherwise be ambiguous.

2. slice(a,b,c) grows an __iter__ method that returns a generator that 
produces an appropriate sequence of integers. This is easy to define for 
positive steps, but tricky for negative steps (more on that in a second).

Thus:

for i in (1::2): print i,
=> 1 3 5 ...

and

for i in (:10:3): print i,
=> 0 3 6 9


The tricky part is deciding what to with negative steps when the start 
is undefined. It's tempting to use 0 as the start, but I think -1 is 
actually better if slightly odd. The reason is that I think the 
following invariant should hold.

newlist = []
for i in someslice:
     try:
         newlist.append(origlist[i])
     except IndexError:
         break
assert(newlist == origlist[slice])

For that to work out, you want:

for i in (::-2): print i,
=> -1 -3 -5 ...

etc. I realize that this is quite similar to the rejected PEP 204 
syntax, but the addition of generators has reduced many of the problems 
that that PEP had.

I have no great need for range literals, but it seems that if there were 
to be one, one that fit together with the existing syntax would be 
better than making up something new.

-tim









More information about the Python-list mailing list