Generators
A generator is a function that returns an object (iterator) which we can iterate over (one value at a time).
Creating a Generator
It is fairly simple to create a generator in Python. It is as easy as defining a normal function with yield
statement instead of a return
statement.
If a function contains at least one yield
statement (it may contain other yield
or return
statements), it becomes a generator function. Both yield
and return
will return some value from a function.
The difference is that, while a return
statement terminates a function entirely, yield
statement pauses the function saving all its states and later continues from there on successive calls.
Let us now see a few examples of generator functions:
The generator can also be used to return a list of values
Advantages of using generator
These functions are better w.r.t. memory utilization and code performance, as they allow function to
avoid doing all work at a time.
They provide a way to manually save the state between iterations. As the variables in function scope
are saved and restored automatically.
Last updated