12. Iterators & Generators#
Learning goals — By the end of this chapter you will be able to:
Explain Python’s iterator protocol (
__iter__/__next__) and useiter()andnext()manuallyUse built-in lazy iterators:
enumerate(),zip(),map(),filter(), andreversed()Build custom iterator classes that implement the full iterator protocol
Write generator functions using
yieldto produce values lazilyCreate generator expressions as a memory-efficient alternative to list comprehensions
Design multi-step data pipelines using chained generators
Iterators and generators are the backbone of Python’s memory-efficient data processing. Everything from for loops to file reading to pandas relies on this protocol.