Python - Function Generator functions

Introduction

The following code defines a generator function that can be used to generate the squares of a series of numbers:

def gensquares(N): 
   for i in range(N): 
       yield i ** 2        # Resume here later 

This function yields a value by using yield statement.

When using yield statement, it returns value to its caller, each time through the loop and when it is resumed, its prior state is restored.

Demo

def gensquares(N): 
   for i in range(N): 
       yield i ** 2        # Resume here later 
#  ww w .  j  ava2  s. com
for i in gensquares(5):     # Resume the function 
   print(i, end=' : ')      # Print last yielded value

Result

To end the generation, functions either use a return statement with no value or fall off the end of the function body.

To see what is going on inside the for, call the generator function directly:

Demo

def gensquares(N): 
   for i in range(N): 
       yield i ** 2        # Resume here later 
       # from  w  w  w .  j  a va2s .c  o  m
x = gensquares(4) 
print( x )

Result

x is a generator object that supports the iteration protocol.

The returned generator object has a __next__ method that starts the function or resumes it from where it last yielded a value.

It raises a StopIteration exception when the end of the series of values is reached.

Demo

def gensquares(N): 
   for i in range(N): 
       yield i ** 2        # Resume here later 
       # www.  ja  va2  s.c  o  m
x = gensquares(4) 
print( x )


print( next(x) )            # Same as x.__next__() in 3.X 
print( next(x) )            # Use x.next() or next() in 2.X 
print( next(x) )
print( next(x) )
print( next(x) )

Result

generators return themselves for iter.

Demo

def gensquares(N): 
   for i in range(N): 
       yield i ** 2        # Resume here later 
       # from www.j  a  v a 2s  .c  om
y = gensquares(5)           # Returns a generator which is its own iterator 
iter(y) is y                # iter() is not required: a no-op here 
print( next(y) )            # Can run next()immediately

Result

Related Topics