a pyrex-inspired for-i-from-1-to-n construct backported to Python.Good idea? Bad Idea? PEP?

Peter Hansen peter at engcorp.com
Wed Apr 2 10:02:15 EST 2003


WP wrote:
> 
> Greg Ewing wrote the following Pyrex snippet:
> >     for i from 0 <= i < n:
> >       result.append(a[i])
> 
> This pyrex snippet reminds me (because of its orthogonality to C) of one
> thing, more than tab indents, that I have always thought was bogus in Python,
> which is the handling of integer loops.  range(0,n) sucks, xrange(0,n) is an
> interesting hack which obscures the readability of code, and post 2.x versions
> of python, with generators, and other 'inverted' ways of accomplishing the
> obvious procedural effect of an integer for loop, are all just ways of
> obfuscating otherwise perfectly readable python code. Okay, so I'm being
> opinionated. I know that. But does anyone else thing that for the extremely
> common (and therefore bytecode optimizeable, syntax customizeable) case where
> you need to do a for loop over a range (possibly large range) of integers,
> that a language level keyword construct (such as the above) would be
> preferable 

I just scanned a few tens of thousands of lines of our code, and as near
as I can tell only 13 cases out of over 160 instances of "for" loops are
using range() or xrange().  This backs up my personal feeling that in
Pythonic code, it's actually rare to iterate over an integer range 
specified with simple upper and lower bounds like that, and certainly not
common enough to justify special syntax.

I can't agree with the desire to make this a special case, when range()
provides such a simple, clean answer.

-Peter




More information about the Python-list mailing list