Dremendo Tag Line

Generators in Python Programming

Function in Python

In this lesson, we will understand what is Generators in Python Programming and how to create them along with some examples.

What are Generators in Python Programming?

Generators are functions that return multiple values using a yield statement. The yield statement returns the elements from a generator function in a generator object which can be traversed using a loop.

video-poster

Generators Example 1

'''This is a simple generator function that
returns the multple of any given number'''

def multiple(num):
    for i in range(1,11):
        yield num*i


'''This function prints the multiple of the
given number returned from the generator
function using a for loop'''

for n in multiple(5):
    print(n)

Output

5
10
15
20
25
30
35
40
45
50

Generators Example 2

'''This is a simple generator function that
returns fibonacci numbers till nth terms'''

def fibonacci(nth):
    a=1; b=0; c=0
    for i in range(1,nth+1):
        c=a+b
        yield c
        a=b
        b=c


'''This function prints fibonacci numbers
returned from the generator function using a for loop'''

for n in fibonacci(10):
    print(n,end=' ')

Output

1 1 2 3 5 8 13 21 34 55

The above two examples show how we can return multiple values using a generator function. When a yield statement executes, it temporary halt the function's execution inside which it is declared and sends the value back to the caller statement. The yield statement remembers the state of the function where it left off and returns to resume the function and execute the next yield statement.