How to create generators

How to create generators

The generator is just like a function. Rather than return value it yields value. Any function that contains a yield statement is called a generator.

We can yield several values one by one. Each time a value is yielded with yield statement, the function freezes and waits to be reawakened. When it is called again, it resumes its execution at the point where it stopped.

We can make use of all the values by iterating over the generator:


nested = [[1, 2], [3, 4], [5]] #   ww w  .  ja  va2 s  . c o m

def flatten(nested): 
    for sublist in nested: 
        for element in sublist: 
            yield element 


for num in flatten(nested): 
    print num 

list(flatten(nested)) 

Recursive generator


def flatten(nested): 
    try: # w  w  w.  jav a 2  s  .co m
        for sublist in nested: 
            for element in flatten(sublist): 
                yield element 
    except TypeError: 
        yield nested 

list(flatten([[[1],2],3,4,[5,[6,7]],8])) 

When flatten is called, there are two possibilities: the base case and the recursive case. In the base case, the function is told to flatten a single element, in which case the for loop raises a TypeError, and the generator simply yields the element.

If it is a list, we go through all the sublists and call flatten on them. Then you yield all the elements of the flattened sublists by using another for loop.

Fibonacci sequences using generators


def fibonacci(max):
    a, b = 0, 1# from w w w.  j  a v a  2 s  .  c  o  m
    while a < max:
        yield a
        a, b = b, a+b

for n in fibonacci(1000):
    print n,

The code above generates the following result.

yield statement works with for loop


def gensquares(N):
     for i in range(N):
         yield i ** 2               # resume here later
#  ww  w.j a  v  a2 s  . com
for i in gensquares(5):        # resume the function 
     print i, ':',              # print last yielded value


x = gensquares(10)

x.next()
x.next()
x.next()

def buildsquares(n):
     res = []
     for i in range(n): res.append(i**2)
     return res

for x in buildsquares(5): print x, ':',


for x in [n**2 for n in range(5)]:
     print x, ':',


for x in map((lambda x:x**2), range(5)):
     print x, ':',

The code above generates the following result.





















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules