Thursday, March 13, 2014

Python Yield versus Return

As coders, we are familiar with how function calls work in Python or C.  Whenever we call a function, the function gets a private namespace where its local variables are created.

Return
The return statement is where all the local variables are destroyed and the resulting value is given back (returned) to the caller.  Should the same function be called some time later, the function will get a fresh new set of variables.

Yield
But what if the local variables aren't thrown away when we exit a function?  This implies that we can resume the function where we left off.  This is where the concept of generators are introduced and the yield statement resumes where the function left off.

Here's a simple example:

def generate_integers(N):   
     for i in range(N): 
         yield i

No comments:

My Profile

My photo
can be reached at 09916017317