Instagram
youtube
Facebook
Twitter

Generators

What is Python Generator?

Python Generators are the most easiest way of creating iterators.

Simply speaking, a generator is a function that returns an object(iterator) that we can iterate over(one value at a time).

How to Create Generators in Python?

Creating generators in python is very simple.

To create a generator you need to replace return statement from normal function with a yield statement.

The difference between yield and return statement is that , return statement stops or terminates a function entirely.

While yield statement parses the fucntion saving all its states and later continues from there on successive calls.

# A simple generator function
def my_gen():
    n = 1
    print('This is printed first')
    # Generator function contains yield statements
    yield n

    n += 1
    print('This is printed second')
    yield n

    n += 1
    print('This is printed at last')
    yield n

>>> # It returns an object but does not start execution immediately.
>>> a = my_gen()

>>> # We can iterate through the items using next().
>>> next(a)
This is printed first
1
>>> # Once the function yields, the function is paused and the control is transferred to the caller.

>>> # Local variables and theirs states are remembered between successive calls.
>>> next(a)
This is printed second
2

>>> next(a)
This is printed at last
3

>>> # Finally, when the function terminates, StopIteration is raised automatically on further calls.
>>> next(a)
Traceback (most recent call last):
...
StopIteration
>>> next(a)
Traceback (most recent call last):
...
StopIteration

 

Generator using Loop

# A simple generator function
def my_gen():
    n = 1
    print('This is printed first')
    # Generator function contains yield statements
    yield n

    n += 1
    print('This is printed second')
    yield n

    n += 1
    print('This is printed at last')
    yield n


# Using for loop
for item in my_gen():
    print(item)