Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Update

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.

like image 586
Dzyann Avatar asked Jul 17 '15 20:07

Dzyann


People also ask

Is Python range a generator?

A comprehensive practical guide The generators in Python are one of those tools that we frequently use but do not talk about much. For instance, most for loops are accompanied with the range function which is a generator. Generators allow for generating a sequence of values over time.

How do generators work Python?

A Python generator is a function that produces a sequence of results. It works by maintaining its local state, so that the function can resume again exactly where it left off when called subsequent times. Thus, you can think of a generator as something like a powerful iterator.

How does yield work in Python?

What Is Yield In Python? The Yield keyword in Python is similar to a return statement used for returning values or objects in Python. However, there is a slight difference. The yield statement returns a generator object to the one who calls the function which contains yield, instead of simply returning a value.

Why is in range so fast Python?

The reason that the range() function is so fast in Python3 is that here we use mathematical reasoning for the bounds, rather than a direct iteration of the range object.


1 Answers

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(...))
like image 96
jvdm Avatar answered Oct 14 '22 13:10

jvdm