Status of PEP's?
David Eppstein
eppstein at ics.uci.edu
Fri Mar 1 17:45:21 EST 2002
In article <mailman.1015019284.27486.python-list at python.org>,
James_Althoff at i2.com wrote:
> 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
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.
Again, let's consider closed intervals.
If from <= to:
range(from,to+1)
If from > to:
range(from,to-1,-1)
You could sort of avoid this by using a signum function:
range(from,to+signum(from-to),signum(from-to))
but (besides being confusing) this breaks when from=to.
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:
...
--
David Eppstein UC Irvine Dept. of Information & Computer Science
eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/
More information about the Python-list
mailing list