Programming with Python · free preview
Iterators and Generators
See what a for loop really does, write functions that yield a sequence lazily, and pipeline data without building lists.
1. Overview
Overview
2. What a for Loop Really Does
What a for Loop Really Does
3. Functions That Yield
Functions That Yield
4. Lazy Pipelines
Lazy Pipelines
5. Running Total Generator
Running Total Generator
6. First Big Reading
First Big Reading
7. Predict generator exhaustion
For gen = fibonacci(3), list(gen) produces [0, 1, 1]. What does a second list(gen) produce? Give the exact list.
8. Trace a generator with next calls
Follow a lazy producer through three advances and exhaustion.
Example. Trace a generator with next calls
Problem. Follow a lazy producer through three advances and exhaustion.
Correct solution.
Step 1, define the generator.
def running_total(values):
total = 0
for value in values:
total += value
yield totalStep 2, call and inspect the object.
stream = running_total([5, 10, 20])
print(type(stream).__name__)Output.```output generator
Reasoning, calling the function creates the generator; the body has not run yet.
Step 3, advance three times.
```python
print(next(stream))
print(next(stream))
print(next(stream))Output.```output 5 15 35
Reasoning,`total` is 5, then 15, then 35; local state survives across yields.
Step 4, exhaust it.
```python
print(next(stream, 'done'))
print(list(stream))Output.``output done [] ``
Reasoning, a generator is single-use; an exhausted generator does not restart.
关键提醒。
A generator function returns a lazy object; yield preserves local state; exhausted generators produce nothing.
9. Retrieval practice
Use this new input without looking back, values = [4, 2, 8]. Write the generator expression that doubles each value, state the result of list() after it, state the result of a second consumption, and explain the difference.
Give the expression and both consumption results.
10. Mastery check
Apply generators to a new stream requirement, given readings = [36.5, 38.4, 37.2, 39.1], write a lazy expression that yields only fever readings rounded to one decimal place, then give the exact output of printing the list once.
Give the lazy expression and exact output.
Practice this interactively
Free account · instant grading · spaced review that schedules itself.
Start this course for free