In Python, generators are a type of iterable, similar to lists or tuples. However, unlike lists or tuples, generators do not store all the values in memory at once. Instead, they generate values on the fly as you iterate over them. This can be more memory-efficient, especially when dealing with large datasets.
- Generators are created using functions with the
yield
statement. - When a generator function is called, it returns an iterator, but the function’s code is not executed immediately.
- The code is executed only when the iterator’s
__next__()
method is called, and it runs until it encounters ayield
statement. - At that point, the generator yields the value, and the function’s state is saved.
- The next time
__next__()
is called, the function resumes execution right after theyield
statement.
The example code below creates a generator that produces the Fibonacci sequence: