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
range creates a list, so if you do
range(1, 10000000)
it creates a list in memory with9999999
elements.
xrange
is a generator, so itis a sequence objectis athat evaluates lazily.
This is true, but in Python 3, range()
will be implemented by the Python 2 xrange()
. If you need to actually generate the list, you will need to do:
list(range(1,100))
xrange returns an iterator and only keeps one number in memory at a time. range keeps the entire list of numbers in memory.
xrange
only stores the range params and generates the numbers on demand. However the C implementation of Python currently restricts its args to C longs:
xrange(2**32-1, 2**32+1) # When long is 32 bits, OverflowError: Python int too large to convert to C long
range(2**32-1, 2**32+1) # OK --> [4294967295L, 4294967296L]
Note that in Python 3.0 there is only range
and it behaves like the 2.x xrange
but without the limitations on minimum and maximum end points.
In Python 2.x:
range
creates a list, so if you do range(1, 10000000)
it creates a list in memory with 9999999
elements.
xrange
is a sequence object that evaluates lazily.
In Python 3, range
does the equivalent of python's xrange
, and to get the list, you have to use list(range(...))
.
Everyone has explained it greatly. But I wanted it to see it for myself. I use python3. So, I opened the resource monitor (in Windows!), and first, executed the following command first:
a=0
for i in range(1,100000):
a=a+i
and then checked the change in 'In Use' memory. It was insignificant. Then, I ran the following code:
for i in list(range(1,100000)):
a=a+i
And it took a big chunk of the memory for use, instantly. And, I was convinced. You can try it for yourself.
If you are using Python 2X, then replace 'range()' with 'xrange()' in the first code and 'list(range())' with 'range()'.
I am shocked nobody read doc:
This function is very similar to
range()
, but returns anxrange
object instead of a list. This is an opaque sequence type which yields the same values as the corresponding list, without actually storing them all simultaneously. The advantage ofxrange()
overrange()
is minimal (sincexrange()
still has to create the values when asked for them) except when a very large range is used on a memory-starved machine or when all of the range’s elements are never used (such as when the loop is usually terminated withbreak
).