PEP 284, Integer for-loops

gbreed at cix.compulink.co.uk gbreed at cix.compulink.co.uk
Thu Mar 7 07:54:16 EST 2002


David Eppstein wrote:

> It's hard to tell without some context (and I'm not convinced a context 
> exists in which this is the loop you want), but if I had to write this 
> loop, without further information on where n came from or whether it's 
> odd or even, I'd probably skip the range() and go for:
> 
>     x = n - 1
>     while x >= 0:
>         ...loop body...
>         x -= 2
> 
> of course, that requires more care about not continuing from the middle 
> of the loop, and you have to look multiple places to even figure out 
> that it's a loop over a progression of integers, but even so I think 
> it's preferable to range(n-1,-1,-2).

I'd still use a range because of all the times I forgot the last line in a 
construct like that, and ended up in a perpetual loop.  If I were going to 
do this sort of thing a lot, adding

def inclusive(start, end, step=1):
        if start<=end:
                return xrange(start, end+1, abs(step))
        else:
                return xrange(start, end-1, -abs(step))

to my utilities library (along with indices()) would be a lot less 
overhead than changing the language.

>>> inclusive(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> inclusive(10,1)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> inclusive(0,10,2)
[0, 2, 4, 6, 8, 10]
>>> inclusive(10,0,2)
[10, 8, 6, 4, 2, 0]

This can give you all the generality of the PEP if you write

for lower op1 var op2 upper:
    ...

as

for var in inclusive(lower, upper):
    if lower op1 var op2 upper:
        ...

which is more verbose but barely less readable.


                      Graham
             
         <http://www.microtonal.co.uk/>



More information about the Python-list mailing list