Change language

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

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically