PEP 284, Integer for-loops

Roy Smith roy at
Thu Mar 7 15:13:03 CET 2002

Peter Hansen <peter at> wrote:
> I think I rarely use for with a range any more, because I tend to
> think "if I need to do something eight times, there are probably 
> eight things I'm doing something to so I should just take those
> things and iterate over a list of them".

That's an interesting way to look at it.

I just took a look at some random collection of python code I've got laying 
around, totaling 6100 lines.  I've got 85 for loops, 12 of which use range, 
the other 73 don't.  What's even more interesting is that of the 12 ranges, 
11 of them are in a single file; the only file of the collection which I 
didn't write (and which I consider pretty ugly code).

I don't remember ever thinking "for x in range is bad, let me see if I can 
write this some other way", it's just a result of the natural way I write 
python code.  I suspect if you look at some of my earlier code, you would 
find a lot more range constucts in it.  Paradigm shift?  Gotten more used 
to the language?  Maybe.

I remember when I was first moving from Fortran to C, I wrote a lot of 
goto's.  Gradually, I evolved that way of thinking out of how I wrote code.  
After many years of C, I got to the point where I would very, very 
occasionally write a goto, most often when needed to do something like 
break out of several nested loops at once.  I *knew* gotos were evil, but 
would convince myself that "yeah, in this special case, you really do need 
to do that".  Python doesn't even have gotos, and I don't miss them.

The one "for x in range" loop that I wrote, was a particularly bletcherous 
piece of code which grovels over strings one character at a time.  Even 
before I did this little experiment, it's the one module I've got which I 
keep saying to myself really needs to be re-written in C.  I think maybe 
the real problem is I wrote this piece of code like I would have written 
the C version, doing very un-pythonic things like:

        for i in range (len (line)):
            c = line[i]
                elif c.isdigit() or c == '-' or c == '.':
                if c == "'":
                    if line[i+1:i+2] == "'":

Python may be a swiss army knife, if you try to do brain surgery with a 
swiss army knife, you'll end up with poor results.  I think the above code 
proves that.

I've been watching the discussion of this PEP somewhat horrified because 
it's a completely gratuitous change which adds nothing of significant 
value.  It's just another special case to confuse people trying to learn 
the language.  Now that I've looked at just how uncommon the "for x in 
range" construct really is, I'm even more convinced the whole idea is just 
plain silly.

More information about the Python-list mailing list