Python – Generators
Python Generators are similar to Iterators, but in iterators we have observed that we need Stop Iteration to ensure that the program does not end up in infinite loop.
To Overcome this, Python has a special feature called Generators. Generators are similar to Iterator objects, but the major difference is the execution processing of statements.
There is a special statement called yield which will ensure that it is a Generator. Being Said that, if a function has one or more yield statements, they are called Generators whereas Iterators have return statements.
The difference in the processing across yield and return is such that yield statement returns the value and pauses the execution to verify and go on to next execution whereas return statement returns the value and terminates the function execution.
Being mentioned above, the return statement can be provided in the Generator Function but the return value for that statement is none.
We need to explicitly create and call iter() and next() functions for Iterator Objects but for Generator Objects we need not explicitly create them. They are taken care of by Generator Objects.
Let us understand Generators with an example below:
def myGen (): print('First') yield 1 print('Second') yield 2 print('Last') yield 3 gen = myGen()