Status of PEP's?

James_Althoff at i2.com James_Althoff at i2.com
Fri Mar 1 18:57:26 EST 2002


[Jim]
> In other words, if I want to iterate up (smaller up to larger) I need to
> write the for-loop as
>     for smaller <= i <= larger:  # can *only* iterate up
> but if I want to iterate down (larger down to smaller) I need to write
the
> for-loop with the reverse relational operators
>     for larger >= i >= smaller:  # can *only* iterate down
>
> So if you want/need "from/to" functionality for an "interval" using the
> suggested for+relational idiom, you need to have two for-loops at hand,
> test the bounds, *and* pick the corresponding, correct for-loop (whose
> relational operators are in the correct direction).
>
> Note that the existing range and xrange functions (when used in a
> for-loop), although requiring a test on the bounds in order to determine
> the correct order of the args, do *not* require the use of two for-loops
in
> this context.
>     for i in range(n,m,step):  # can iterate up or down depending on
> n,m,step


[David Eppstein]
> Ok, I missed your point that the iteration order and not just the
> endpoints are important in your example.
>
> But I think the current range system does too require two loops.

I guess I was still a little fuzzy in my explanation.  I meant this:

(ignore open/closed stuff)

>>>
>>> def printFromTo(start,end):
...   # only dealing with step == 1 or -1
...   step = 1
...   if start > end:
...     step = -1
...   for i in range(start,end,step): # up or down
...     print i
...
>>> printFromTo(5,10)
5
6
7
8
9
>>> printFromTo(10,5)
10
9
8
7
6
>>>


> Anyway, while you may need two ranges, you don't have to have two
> separate for-loops over those ranges:
>     if from <= to: range = [x for from <= x <= to]
>     else: range = [x for from >= x >= to]
>     for x in range:
>         ...

I agree that if you actualize the ranges using list comp.s as shown, then
your one final for-loop is enough.  I was counting list comp.s as "for
loops", also.  But your example shows what I was trying to say.  In this
case you need one list comp for the "up" case and one for the "down" case.
That is the limitation that I was trying to point out.

Jim





More information about the Python-list mailing list