What is generator
Generators are a powerful tool in Python that allow you to create iterable objects on-the-fly. They are functions that use the yield statement instead of return to produce a sequence of values.
Why we need generator
One of the main reasons why we need generators is that they are memory-efficient. When you create a list, for example, all the elements of the list are created and stored in memory at once. If the list is very large, this can consume a lot of memory. Generators, on the other hand, only generate one value at a time as you iterate over them, so they don’t require as much memory.
How generator works
Generators can also be more efficient in terms of computation time. Since they generate values on-the-fly, they can often avoid unnecessary calculations and terminate early if the result is already determined.
|
|
__iter__ and __next__ methods
When the Python interpreter encounters the yield keyword in a generator function, it automatically converts the generator function to a generator object and adds the iter() and next() methods to the object. The implementation of these methods is generated automatically by the Python interpreter and includes the necessary logic to control the generator’s iteration and state.