2

I read this if we want to create a list of 1000000 numbers than using range(1000000) is not a cool idea because that will take a lot memory and soon as this range() is called it creates a list of that input size whereas xrange(1000000) would be better as it creates the values as needed

Say i have this little program:

for i in xrange(1000000):
        print i 

Does this create the next position in the list every time the for loop is called not at the time when we called xrange(1000000) ?

1 Answers1

1

xrange() produces an object that only tracks the start, stop and step values. Nothing else.

Iterating then makes use of those values; the 5th element is always going to be start + (5 * step) anyway, so it just calculates that, rather than create a list like range() does.

To do this while iterating, a separate rangeiterator is created:

>>> xr = xrange(100)
>>> it = iter(xr)
>>> it
<rangeiterator object at 0x100660450>
>>> next(it)
0
>>> next(it)
1

The range iterator knows what step the iteration is at and asks xrange() to produce the next integer for that step.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343