Iterators & Generators

12. Iterators & Generators#

Learning goals — By the end of this chapter you will be able to:

  • Explain Python’s iterator protocol (__iter__ / __next__) and use iter() and next() manually

  • Use built-in lazy iterators: enumerate(), zip(), map(), filter(), and reversed()

  • Build custom iterator classes that implement the full iterator protocol

  • Write generator functions using yield to produce values lazily

  • Create 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.

Chapter flow