efficiency of range() and xrange() in for loops

Georg Brandl g.brandl-nospam at gmx.net
Wed Apr 5 16:17:52 EDT 2006


Steve R. Hastings wrote:
> When you compile the expression
> 
>     for i in range(1000):
>         pass
> 
> does Python make an iterator for range(), and then generate the values
> on the fly?  Or does Python actually allocate the list [0, 1, 2, ..., 999]
> and then step through it?  

It does.

> I was under the impression that recent releases of Python optimize this
> case, but upon reflection, I have no idea where I got that impression.
> 
> If Python actually allocates the list, then clearly we should all use
> "for i in xrange".  But "for i in range" looks cleaner, and is potentially
> more lightweight than xrange.  Of course, if you want to write code that
> runs well on older versions of Python, you need to use xrange().
> 
> 
> If Python doesn't currently optimize this case, is there any chance this
> optimization could be added?

As the alternative is so easy (adding a single character), I think this will
not make it into the 2.x line. A patch for the old compiler existed on SF,
but it will not work with the new AST compiler.

> P.S. It looks like all the cool people look at the generated bytecodes to
> answer questions like this one.  I want to be cool too.  Where can I find
> information about how to get a bytecodes listing for my compiled Python?

The "dis" module.

Georg



More information about the Python-list mailing list