Apparently xrange is faster but I have no idea why it\'s faster (and no proof besides the anecdotal so far that it is faster) or what besides that is different about
Some of the other answers mention that Python 3 eliminated 2.x's range
and renamed 2.x's xrange
to range
. However, unless you're using 3.0 or 3.1 (which nobody should be), it's actually a somewhat different type.
As the 3.1 docs say:
Range objects have very little behavior: they only support indexing, iteration, and the
len
function.
However, in 3.2+, range
is a full sequence—it supports extended slices, and all of the methods of collections.abc.Sequence with the same semantics as a list
.*
And, at least in CPython and PyPy (the only two 3.2+ implementations that currently exist), it also has constant-time implementations of the index
and count
methods and the in
operator (as long as you only pass it integers). This means writing 123456 in r
is reasonable in 3.2+, while in 2.7 or 3.1 it would be a horrible idea.
* The fact that issubclass(xrange, collections.Sequence)
returns True
in 2.6-2.7 and 3.0-3.1 is a bug that was fixed in 3.2 and not backported.