Skip to content Skip to sidebar Skip to footer

What Is The Difference Between Normal Function And Generator Function?

I am trying to understand the below methodology, In [26]: def generator(): ....: print 'generator function hits' ....: for i in range(3): ....: yield i

Solution 1:

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

Solution 2:

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.

Post a Comment for "What Is The Difference Between Normal Function And Generator Function?"