xrange() syntactic sugar

Delaney, Timothy C (Timothy) tdelaney at avaya.com
Thu Jan 8 22:24:36 EST 2004


> From: Christopher T King
> 
> for i in xrange(0,8,2):
> 	pass
> 
> is equivalent to
> 
> for i in 0:8:2:
> 	pass 

This exact syntax has been suggested and rejected a few times now ... it's been suggested a few times on python-dev as well by various luminaries/ I don't think there's a PEP for it though (there probably should be). 

> xrange() objects become an acceptable list index, operating as a slice
> operator does. Example:
> 
> a[0:8:2] is equivalent to a[xrange(0,8,2)]

Urgh! Try instead a[slice(0, 8, 2)} ...

xrange is probably going to be gradually phased out - it's anomalous in this day and age of iterators, generators and other much more general constructs. Instead, range is more likely to be optimised once we've got rid of the option to modify other modules directly (i.e. once you can't rebind __builtins__.range it can be optimised in those cases where it's just used in a for: loop - the most common case).

Tim Delaney




More information about the Python-list mailing list