PYTHON ADVANCED: PROFESSIONAL ENGINEERING MASTERY / L02GENERATORS AND ITERATORS: LAZY EVALUATION MASTERY
课程 · 12 · 02 / 12
LESSON 02 · ADVANCED · 55 MIN · ◆ 4 INSTRUMENTS

Generators and Iterators: Lazy Evaluation Mastery

Understand the iterator protocol, build generators with yield, use generator expressions, and learn about coroutines as a foundation for async.

TIP

Learning Objectives: After this lesson, you'll understand the iterator protocol, build generators with yield, use generator expressions efficiently, and see how generators form the foundation for coroutines and async programming.

Understanding Lazy vs Eager Evaluation

Before diving into code, let's visualize the fundamental difference between eager (list) and lazy (generator) evaluation:

FIG. 02Flow Diagram
INTERACTIVE
LOADING INSTRUMENT
Fig. 02Interactive flow diagrams, timelines, and process visualizations

With lists, all values are computed and stored upfront. With generators, values are computed one at a time as needed, keeping memory usage constant.

The Iterator Protocol

Python's iteration is built on a simple protocol: __iter__ and __next__.

FIG. 04Flow Diagram
INTERACTIVE
LOADING INSTRUMENT
Fig. 04Interactive flow diagrams, timelines, and process visualizations

Understanding Iteration

FIG. 06Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 06Interactive Python code execution environment

Building a Custom Iterator

FIG. 08Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 08Interactive Python code execution environment

Iterable vs Iterator

FIG. 10Memory Visualizer
INTERACTIVE
LOADING INSTRUMENT
Fig. 10Visual representation of memory layout

Use the memory visualizer above to explore how iterables and iterators differ in memory. Iterables can create multiple iterators; iterators maintain state and are single-use.

FIG. 12Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 12Interactive Python code execution environment

Generators: Iterators Made Simple

Generators provide a concise way to create iterators using yield. Let's visualize how a generator suspends and resumes:

FIG. 14Flow Diagram
INTERACTIVE
LOADING INSTRUMENT
Fig. 14Interactive flow diagrams, timelines, and process visualizations

Basic Generators

FIG. 16Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 16Interactive Python code execution environment

Step Through Generator Execution

Use the algorithm stepper below to trace through generator execution step by step:

FIG. 18Algorithm Stepper
INTERACTIVE
LOADING INSTRUMENT
Fig. 18Step-through execution of algorithms and code

How yield Works

FIG. 20Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 20Interactive Python code execution environment

Memory Comparison: Generators vs Lists

FIG. 22Flow Diagram
INTERACTIVE
LOADING INSTRUMENT
Fig. 22Interactive flow diagrams, timelines, and process visualizations
FIG. 24Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 24Interactive Python code execution environment

Generator Expressions

Generator expressions provide a concise syntax for simple generators.

FIG. 26Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 26Interactive Python code execution environment

Advanced Generator Features

yield from - Delegating to Sub-generators

FIG. 28Flow Diagram
INTERACTIVE
LOADING INSTRUMENT
Fig. 28Interactive flow diagrams, timelines, and process visualizations
FIG. 30Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 30Interactive Python code execution environment

Generator Send and Throw

Generators can also receive values, enabling two-way communication:

FIG. 32Flow Diagram
INTERACTIVE
LOADING INSTRUMENT
Fig. 32Interactive flow diagrams, timelines, and process visualizations
FIG. 34Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 34Interactive Python code execution environment

Generator Close and Cleanup

FIG. 36Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 36Interactive Python code execution environment

Practical Generator Patterns

Data Pipeline Processing

FIG. 38Flow Diagram
INTERACTIVE
LOADING INSTRUMENT
Fig. 38Interactive flow diagrams, timelines, and process visualizations

The key insight: data flows on demand. The consumer pulls values through the pipeline, and each stage only processes one item at a time.

FIG. 40Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 40Interactive Python code execution environment

Infinite Sequences

FIG. 42Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 42Interactive Python code execution environment

Memory-Efficient File Processing

FIG. 44Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 44Interactive Python code execution environment

Generators and itertools

FIG. 46Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 46Interactive Python code execution environment

Practice Exercises

Exercise 1: Sliding Window Generator

FIG. 48Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 48Interactive Python code execution environment

Exercise 2: Tree Traversal Generator

FIG. 50Python Code Executor
INTERACTIVE
LOADING INSTRUMENT
Fig. 50Interactive Python code execution environment

Key Takeaways

ConceptDescription
Iterator Protocol__iter__ returns iterator, __next__ returns next value
Generator FunctionFunction with yield, returns generator object
Generator Expression(expr for x in iterable) - lazy list comprehension
yield fromDelegate to sub-generator, simplifies nested iteration
send()Pass values INTO generator (coroutine pattern)
Lazy EvaluationValues computed on-demand, memory efficient

When to Use Generators

  • Large datasets - Process without loading everything into memory
  • Infinite sequences - Fibonacci, primes, streaming data
  • Data pipelines - Chain transformations lazily
  • File processing - Line-by-line without loading entire file
  • API pagination - Fetch pages on-demand

Next Steps

In the next lesson, we'll explore Context Managers and Descriptors—master the with statement, build custom context managers, and understand how descriptors power Python's attribute access.


Ready to manage resources like a pro? Context managers await!


Further Reading

Visualize It

  • Python Tutor — paste a generator function and step through next() calls. Watch local state suspend and resume — the most underrated Python feature in plain sight.

Official Docs

Tutorials

Modern Use Cases

  • Async generators (async def + yield) — used by FastAPI/Starlette streaming responses, OpenAI's streaming API client, etc. PEP 525.
  • PEP 530 — Asynchronous Comprehensions[x async for x in stream].

Books

  • Book: Fluent Python (2nd ed.) — Chapter 17 ("Iterators, Generators, and Classic Coroutines"). The definitive treatment.
  • Book: Effective Python — Items 30–34 cover generators in depth.