Generators in Python

There are two terms when discussing generators.

  1. Generator function : A generator function is defined as a normal function, but whenever you need to generate a value, it does this with the

    # Generator function that produces 1 for the first time
    # 2 second time and 3 third time

    def simpleGeneratorFun ():

    yield 1  

    yield 2  

    yield 3  

     
    # Driver code to test over generator function

    for value in simpleGeneratorFun (): 

    print (value)

    Output:

     1 2 3 
  2. Generator-Object: generator functions return a generator object. Generator objects are used either by calling the following method on the generator object, or by using the generator object in a “for in” loop (as shown in the above program).

    # Python program to demonstrate usage
    # object generator with next ()

     
    # Generator function

    def simpleGeneratorFun ():

    yield 1

    yield 2

    yield 3

      
    # x - generator object

    x = simpleGeneratorFun ()

     
    # Loop through the generator object using next

    print (x. next ());  # In Python 3 __next __ ()

    print (x. next ()); 

    print (x. next ()); 

    Output:

     1 2 3 

So the generator function returns a generator object that is iterative, that is, it can be used like Iterators .

For another example, here`s a Fibonacci number generator.

# Simple generator for Fibonacci numbers

def fib (limit):

 

# Initialize the first two Fibonacci numbers

a, b = 0 , 1

  

# One by one inferior to the next Fibonacci number

while a & lt; limit:

yield a

a, b = b, a + b

 
# Create object generator

x = fib ( 5 )

 
# Loop through the generator object using next

print (x. next ());  # In Python 3 __next __ ()

print (x. next ()); 

print (x. next ()); 

print (x. next ()); 

print (x. next ()); 

 
# Loop through the generator object using for
# in a loop.

print ( "Using for in loop" )

for i in fib ( 5 ): 

print (i)

Output:

 0 1 1 2 3 Using for in loop 0 1 1 2 3 

Applications: Suppose we are creating a stream of Fibonacci numbers, applying the approach generator makes it trivial; we just need to call next (x) to get the next Fibonacci number without worrying about where or when the stream of numbers ends. 
A more practical type of stream handling — processing large data files such as log files. Generators provide an efficient way to do this because only portions of the file are processed at a time. We can also use Iterators for these purposes, but Generator provides a quick way (we don`t need to write __next__ and __iter__ methods here).

Link below for more advanced generator applications in Python. 
http://www.dabeaz.com/finalgenerator/

This article is courtesy of Shwetanshu Rohatgi . Please post comments if you find something wrong or if you would like to share more information on the topic under discussion