Python Generator

The generator is a special type function, which is responsible to generate a sequence of values. We can write a generator function just like an ordinary function, but it uses a special keyword called yield to return values.

The following example demonstrates the generator function to generate 3 values "A", "B", "C"

def mygen():
    yield "A"
    yield "B"
    yield "C"
    
values=mygen()
'''print(next(values))
print(next(values))
print(next(values))
print(next(values))'''
for num in values:
    print(num)

The output is:

genearating-three-values

The following example demonstrates the generator function to generate the first n values

def first_n_values_generator(n):
    i=1
    while i<=n:
        yield i
        i=i+1
        
num=first_n_values_generator(10)
for x in num:
    print(x)

The output is:

generating-first-n-values

The following example demonstrates the generator function to generate values for the countdown with provided max values

def countdown_generator(num):
    while num>=1:
        yield num
        num=num-1
        
info=countdown_generator(10)
for x in info:
    print(x)        

The output is:

generating-values-in-countdown-manner

The following example demonstrates the generator function to generate a Fibonacci number

Fibonacci numbers: The next number is the sum of the previous two numbers
ex:0,1,1,2,3,5,8,13....etc..
def fibonacci_sequence_generator():
    a,b=0,1
    while True:
        yield a
        a,b=b,a+b
        
values=fibonacci_sequence_generator()
for x in values:
    if x <=10:
        print(x)
    else:
        break

The output is:

generating-fibonacci-numbers

If we want to generate the first 10 Fibonacci numbers, then

def fibonacci_sequence_generator():
    a,b=0,1
    while True:
        yield a
        a,b=b,a+b
        
values=fibonacci_sequence_generator()
count=1
while count<=10:
    print(next(values))
    count=count+1

The output is:

generating-first-10-fibonacci-number

The following example demonstrates the performance comparison between the collections and generator

import random
import time
names=['Ravi','Raju','Renu','Rocky']
subjects=['Python','Java','Datascience']

def student_list(num):
    results=[]
    for i in range(num):
        student={'id':i,'name':random.choice(names),'subject':random.choice(subjects)}
        results.append(student)
    return results

t1=time.perf_counter()
students=student_list(100000)
t2=time.perf_counter()
print("The Time taken to prepare student list:",t2-t1)    

def student_generator(num):
    for i in range(num):
        student={'id':i,'name':random.choice(names),'subject':random.choice(subjects)}
        yield student
        
t1=time.perf_counter()
student=student_generator(100000)
print("The Time taken to prepare student generator:",t2-t1)        

The output is:

practcal-proof-for-cllections-vs-generators

So, the above output shows you that the time taken to prepare the student list is greater when compared with the generators.

A Function as a return value or A Function as an Argument to the Function

The Advantages and Limitations of Generator

Advantages :

  • When compared with Class Level Iterators, Generators are very easy to use.
  • Improves Memory Utilization and Performance.
  • Generators are best suitable for reading Data from a Large Number of Large Files.
  • Generators work great for web scraping and crawling.

Limitations :

  • The Generator won't store any data
  • We cannot ask a particular element

The difference between Decorator and The Generator

Decorator Generator
If we want to extend the functionality of any existing function without modifying it then we should go for Decorator If we want to generate a sequence of values then we should go for generators
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions