Dzyann Dzyann - 3 months ago 11
Python Question

Does the Python range generator generate all values or yields them progressively?

When you do something like this:

for i in range(5):
print i

What does Python do? Does it first generate an array with [0,1,2,3,4] and then goes over each item printing it?
Similar to:

for i in [0,1,2,3,4]:
print i

Or does it print each number as it generates them? Something like:

Generate 0 assign 0 to i print i

Generate 1 -> assign 1 to i -> print i

Generate 2 -> assign 2 to i -> print i

Generate 3 -> assign 3 to i -> print i

Generate 4 -> assign 4 to i -> print i


I have added the tag for Python 2.7. I didn't think my question was version specific, but it seems it is!

Right now I am working with Python 2.7 so my question refers to that. But I find very valuable the information comparing Python 2 range against Python 3 range.


In Python 2, range() returns the whole list object then that list object is iterated by for.

In Python 3, it returns a memory efficient iterable, which is an object of its own with dedicated logic and methods, not a list. Now for will get each value as it is generated by that iterable.

In Python 2 there is xrange() to get something like what Python 3's range() do. Python 2's xrange is kind of halfway between Python 2's range and Python 3's range. It's better than the former but not as good as the latter.

Finally, in Python 3, if you want the whole list do:

>>> list(range(...))