What is a generator in Python?

Last updated 3 weeks, 5 days ago | 21 views 75     5

Tags:- Python

Python | Generator

Functions that return an iterable set of items are called generators. It is a normal function except that it yields expression in the function. It does not implements __itr__ and next() method and reduces other overheads as well.

 

If a function contains at least a yield statement, it becomes a generator. The yield keyword pauses the current execution by 
saving its states and then resume from the same when required.

 

def my_fun(x):
    for i in range(x):
        yield i*i


for sqr in my_fun(5):
    print(sqr)

Output:

0
1
4
9
16