11. Iterators & Generators#
Iterators and generators are the backbone of Python’s memory-efficient data processing.
The iterator protocol:
__iter__and__next__Built-in lazy iterators
Custom iterator classes
Generator functions and generator expressions
Lazy pipelines for streaming data
Video
This overview introduces generator functions and lazy value production with yield.
Learning Goals
By the end of this chapter, you will be able to:
Explain Python’s iterator protocol and use
iter()andnext()manuallyUse built-in lazy iterators such as
enumerate(),zip(),map(),filter(), andreversed()Build custom iterator classes that implement the iterator protocol
Write generator functions with
yieldDesign multi-step data pipelines using chained generators