range syntax

Colin J. Williams cjw at sympatico.ca
Sat Nov 11 16:09:02 CET 2006


Fredrik Lundh wrote:
> Colin J. Williams wrote:
> 
>> One of the little irritants of Python is that the range syntax is rather 
>> long-winded:
>> [Dbg]>>> range(3, 20, 6)
>> [3, 9, 15]
>> [Dbg]>>>
>> It would be nice if one could have something like 3:20:6.
> 
> if you find yourself using range a lot, maybe you should check if you 
> couldn't use custom iterators more often.
> 
> or use the R helper:
> 
>  >>> R[3:20:6]
> [3, 9, 15]
>  >>> R[:20]
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>  >>> R[0:20:2]
> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>  >>> R[1:20:2]
> [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
> 
> where R is defined as:
> 
>  >>> class R:
> ...     def __getitem__(self, slice):
> ...             return range(*slice.indices(slice.stop))
> ...
>  >>> R = R()
> 
> </F>
> 
Thanks, this appears to be a bit neater than the numpy version.  On the 
other hand, the numpy version provides a wider functionality.

R[start, stop, increment] is certainly a little simpler than 
range(start, stop, increment).  However, could we not achieve that with:
 >>> R= range
 >>> R(2, 20, 3)
[2, 5, 8, 11, 14, 17]
 >>>

Your point about iterators is well taken, but it seems that the range is 
used sufficiently frequently that some syntactic form would be helpful.

Colin W.




More information about the Python-list mailing list