How much does Python optimize?

Scott David Daniels scott.daniels at acm.org
Fri Mar 3 13:06:45 EST 2006


Blackbird wrote:
> I think
> 
> for i in range(10):
>     <some code that depends on i>
> 
> is more readable than a while loop with explicit incrementation of i.

> However, range(10) in the command interpreter obviously returns a list.  Is
> this list optimized away in the code above, or is it actually constructed
> internally? (With, say, CPython in one of the recent versions.)

Yup, and if you are tuning a piece of code to the wall, you should time
it and possibly care.  Likely you are not, and the timing makes no
difference.  Someday, range will behave like xrange automagically,
and in the meantime your code will read just fine.  If you are in
trouble now, your code reads much more like:
     for i in range(100000):
         ...

The general rule is make the code clear, measure if its too slow,
and "don't worry, be happy (yagni)."

--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list