range syntax

Fredrik Lundh fredrik at pythonware.com
Fri Nov 10 12:12:55 EST 2006


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>




More information about the Python-list mailing list