What is the difference between range and xrange functions in Python 2.X?


Question

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

for i in range(0, 20):
for i in xrange(0, 20):
1
682
11/26/2014 9:17:34 AM

Accepted Answer

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(...)).

770
8/16/2019 6:05:27 PM

range creates a list, so if you do range(1, 10000000) it creates a list in memory with 9999999 elements.

xrange is a generator, so it is a sequence object is a that 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))

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon