python loops

Nicko usenet at nicko.org
Sat Sep 2 05:04:27 EDT 2006


Fredrik Lundh wrote:
> Michael.Coll-Barth at VerizonWireless.com wrote:
>
> > I thought the xrange was preferred?  for x in xrange(length):
>
> preferred by premature optimization freaks, perhaps.

There's a huge difference between not being profligate with resources
and premature optimisation. In the case of the idiom "for i in
range(x):..." there absolutely no utility whatsoever in creating and
recording the list of objects. Unless it makes a difference to code
structure or maintainability, I think that not creating stacks of
objects you don't need is basic code hygiene and not freakish premature
optimisation.

>   in practice, if the
> range is reasonably small and you're going to loop over all the integers,
> it doesn't really matter.

This is true, but getting into habits that don't matter most of the
time, but have an performance and stability impact some of the time, is
worth discouraging.

> (the range form creates a list and N integers up front; the xrange form
> creates an iterator object up front and N integers while you're looping.
> what's faster depends on what Python version you're using, and some-
> times also on the phase of the moon)

Using range() is only faster on lists so small then the cost is tiny
anyway. On any substantial loop it is quite a bit slower and has been
since python 2.3

Nicko




More information about the Python-list mailing list