2

I am trying to understand the below methodology,

In [26]: def generator():
   ....:     print 'generator function hits'
   ....:     for i in range(3):
   ....:         yield i
   ....:         

In [27]: def normal():
   ....:     print 'normal function hits'
   ....:     return range(3)
   ....: 

In [28]: gen = generator()

In [29]: type(gen)
Out[29]: generator

In [30]: fun = normal()
normal function hits

In [31]: type(fun)
Out[31]: list

Here my research from the above code, 26 is the generator() function and 27 is the normal() function, when I have assigned generator() function to gen variable I haven't seen any print message like generator function hits, But if I have assigned the normal() function to fun variable, I have seen the print message like normal function hits. My question is why generator() function not hit ?

user2864740
  • 60,010
  • 15
  • 145
  • 220
dhana
  • 6,487
  • 4
  • 40
  • 63
  • possible duplicate of [What can you use Python generator functions for?](http://stackoverflow.com/questions/102535/what-can-you-use-python-generator-functions-for) (The answers lie in here, even if answered in a longer-winded manner.) – user2864740 Mar 06 '14 at 04:29

2 Answers2

4

Because a generator function's body is not executed until you call next on it.

>>> gen = generator()
>>> next(gen)
generator function hits
0

Now on the second next() call the generator will run again from where it left off:

>>> next(gen)
1
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
3

Generator function stops at yield, next you call again it resumes from where yield stopped. xrange is also built-in generator version of range function. Since range returns list, xrange generates numbers on demand, memory efficiency is on the side of xrange.

Melug
  • 1,023
  • 9
  • 14