Any *disadvantage* to using xrange() instead of range()?

Michael P. Reilly arcege at shore.net
Thu Jul 8 13:50:48 EDT 1999


Bob Alexander <bobalex at ix.netcom.com> wrote:
: ...even for iteration over a small sequence of integers?

: My intuition would be that xrange() is the preferred way to iterate over a
: numeric sequence, but the documentation seems to go out of its way to stress
: that the advantage of xrange() over range() is minimal -- almost seems to be
: discouraging us programmers from using it unless we have a "memory-starved"
: machine.

: Is there any reason why xrange() should not be the "idiomatic" way to
: iterate over a sequence of integers?

: -- Bob

The range() function has been shown to be faster for small numbers (<100?).
But when the number gets larger, and especially within a nested loop,
the range() function can be far less efficient.

I've never really delved into the the code to find out _exactly_ why it
is faster for smaller numbers, but it makes sense.  For-loops are
optimized for sequences, not sequencable objects (like a xrange
object).  Once the sequence size gets too large, the creation time
become a factor, and slows the loop down on average (not each iteration,
but the entire execution time of the loop).

  -Arcege





More information about the Python-list mailing list