efficiency of range() and xrange() in for loops
Fredrik Lundh
fredrik at pythonware.com
Thu Apr 6 16:35:32 EDT 2006
Carl Banks wrote:
> > I wondered if the Python compiler could, as a special case, turn:
> >
> > for i in range(n)
> >
> > into compiled code equivalent to
> >
> > for i in itr
> >
> > where "itr" is a lightweight iterator that returns the same values as
> > iter(range(n)).
>
> Nope, out of the question for Python 2.x. Note that the the builtin
> range could be rebound, or a global range could appear in the module,
> at run time. There might even be a good reason to do so.... Point is,
> optimizing the call to range can break compatibility even in the for
> loop.
that could of course be addressed by turning for-in into a special method
on the range object... map
for variable in expression:
block
to
_value = expression
try:
_for = _value.__for__
except AttributeError:
_for = iter(_value).__for__
_for(variable, block)
and tweak as necessary.
</F>
More information about the Python-list
mailing list