Python: generators and lazy evaluation¶
A generator produces values on demand. It is useful when the input is large or when a pipeline can process one item at a time.
| squares.py | |
|---|---|
The generator keeps only its current state, so its auxiliary space is \(O(1)\).
Collecting all results with list(squares(n)) instead requires \(O(n)\) space.
One pass
A generator is exhausted after iteration. Create another generator if you need to iterate again.