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.
A normal function
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.
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:
#python #python3 #python-programming #generator