When I started learning Python, I found generators concept a bit tricky to understand easily. So, here’s my take on explaining generators in a simplified manner for anyone to get started with.

In a normal function, ‘return’ statement not only returns the output of the function but also completes its execution.

Image for post

A normal function

How is generator function different?

Generator function uses ‘yield’ statement to give output instead of return statement.

Unlike ‘return’ statement, ‘yield’ statement need not complete the execution of function once it is called. Instead it can be called multiple times to generate successive outputs from the function.

How to create a generator?

Calling generator function returns a ‘Generator’ object. Generator is an iterator and so it supports ‘for’ loop and ‘next’ method to get its outputs.

Using ‘for’ statement to get output from generator:

Image for post

#python #python3 #python-programming #generator

Generators in Python  -  Simplified
1.85 GEEK