[Tutor] Efficiency of while versus (x)range

Wayne Werner waynejwerner at gmail.com
Thu Mar 17 02:23:50 CET 2011

On Wed, Mar 16, 2011 at 7:32 PM, Shane O'Connor <spiderbabymass at gmail.com>wrote:

> Hi,
> First-time poster here. I've a question about loop efficiency - I was
> wondering whether this code:
> i = 0
> while i < 1000:
>     do something
>     i+=1
> is more efficient than:
> for i in range(1000):
>     do something
> or:
> for i in xrange(1000):
>     do something
> In my mind, the while loop should not allocate as much memory as range or
> have the overhead of the iterator of xrange (although aesthetically, I
> prefer the x/range style). Is this the case or does the compiler do
> something clever here?
> In particular, I'm using Python 2.4.3 on a web server which needs to run as
> fast as possible using as little memory as possible (no surprises there!).
> I'm aware that there are more significant optimizations than the above and I
> will profile the code rather than prematurely optimize loops at the sake of
> readability/errors but I'm still curious about the answer.

Well, I'm not sure about the xrange v while loop, but I'm 100% certain that
range is the least efficient of all -  because you both create the iterator
*and* a list to iterate over it. My guess is that xrange v while is fairly
similar, I do know that the for loop raises/catches a StopIteration under
the hood, so there may be some performance issues - I don't think you'll get
a big gain unless you're running the loop thousands+ times, but I could be

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110316/f8ddb268/attachment-0001.html>

More information about the Tutor mailing list