Next / Previous / Contents / TCC Help System / NM Tech homepage

20.46. xrange(): Arithmetic progression generator

The xrange() function has exactly the same arguments as the range() function (see Section 20.33, “range(): Generate an arithmetic progression as a list”).

The difference is that xrange() is a generator (see Section 24.3, “Generators: Functions that can produce a sequence of values”), while range() actually builds a list for its result. This means you can use xrange() in situations where you want to generate a large series of the values from an arithmetic progression, but you don't have enough memory to build that series as a list.

>>> for i in xrange(2000000000):
...     print i,
...     if i > 8:
...         break
... 
0 1 2 3 4 5 6 7 8 9
>>> for i in range(2000000000):
...     print i,
...     if i > 8:
...         break
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
MemoryError