a pyrex-inspired for-i-from-1-to-n construct backported to Python. Good idea? Bad Idea? PEP?
Greg Ewing (using news.cis.dfn.de)
ckea25d02 at sneakemail.com
Thu Apr 3 02:34:46 CEST 2003
> Greg Ewing wrote the following Pyrex snippet:
> > for i from 0 <= i < n:
> > result.append(a[i])
> does anyone else thin[k] that for the extremely common ... case
> where you need to do a for loop over a range ... of integers, that a
> language level keyword construct ... being expressed in a bytecode
> optimized fashion would be good?
The idea for the above syntax came out of an earlier discussion
about this. In a Python context, the main motivation for it wasn't
speed -- as has been pointed out, there are ways that integer
for-loops could be optimised that don't require language changes.
Rather, the motivation was readability and expressiveness. The
things I like about it are that it gives very clear and unambiguous
control over the inclusion or exclusion of both endpoints and
the direction of iteration.
Contrast this with range(m, n, s), which only gives you one
option inclusion of each endpoint, and if s is negative, there
are a number of different and equally plausible things it could
The range() function with one argument is very useful if you
want to generate indices for a sequence, where it does just
what you want; but if you're using the indices for something
else that has nothing to do with sequences, it's just as
likely to do a rather poor job.
J. P. Calderone (exarkun at intarweb.us):
> Hopefully something better than that Pyrex-style loop you've got above.
Actually, I'd like to make it just
for 0 <= i < n:
This is what I wanted to do originally; the "i from" was added
to make it easier to parse. Having had some experience of using
it now, I'm feeling that my original instinct was right. I'm
going to have a go at getting rid of the "from" some day.
> (How do you do steps with that, anyway?)
You don't -- you map a sequence with step 1 to whatever
other sequence you want.
I'm not inclined to try to shoehorn a step into it, because
it would spoil the symmetry. The way it is, the two endpoints
are treated identically. With a step, one of them would have
to be singled out as the "starting" value, which would always
be hit, with the other one possibly being hit or not depending
on the circumstances. Then you're well on the way towards
getting back all the ugliness of range(m, n, s).
Greg Ewing, Computer Science Dept,
University of Canterbury,
Christchurch, New Zealand
More information about the Python-list