Comprehensions and Generators
Transform iterables with readable comprehensions, consume generator expressions lazily, and decide when an explicit loop communicates the rule better.
Before this lesson
Write readable comprehensions
Explain lazy generator consumption
Avoid dense expression pipelines
The short answer
A comprehension builds a collection from an iterable; a generator expression yields values on demand. Use a single transformation and optional filter when it stays readable. Switch to a named function or loop for multiple decisions or side effects.
Build the mental model
List, set, and dictionary comprehensions state the output expression, source iterable, and optional filter together. They are valuable when that complete rule fits comfortably on one line and each name remains meaningful.
The central idea in this lesson is declarative iteration. Read the rule, predict a concrete outcome, and then run the smallest example that can confirm or reject the prediction. This separates knowledge from familiarity with syntax.
Make the design choice explicit
A generator expression does not materialize all results. Functions such as sum, any, all, min, max, and next can consume it incrementally. This reduces memory but generators are usually single-use, so store a list if results need repeated traversal.
measurements = [12, -1, 18, 0, 25, 31]
valid = [value for value in measurements if 0 <= value <= 30]
squares = (value * value for value in valid)
print(valid)
print(sum(squares))Expected output
[12, 18, 0, 25] 1093
Trace the example before running it. Identify each input, transformation, returned value, and side effect. Then change one boundary value and explain why the new behavior follows from the rule rather than memorizing the output.
Recognize failure modes
Do not hide logging, mutation, exception handling, or several nested conditions inside a comprehension. A clear loop is not inferior. Beware that creating a generator does not execute its body until consumption.
Use a professional practice loop
Turn the concept into a repeatable workflow: write down the expected behavior, implement one coherent change, run a representative example, and retain a regression check. If the result surprises you, capture the exact input and error before changing anything.
Review the program for names, boundaries, and hidden side effects. A solution is complete when another developer can understand its contract, reproduce its setup, and verify both the successful path and one meaningful failure path.
Quick knowledge check
Answer before you reveal.
01When does a generator expression perform its calculation?
When a consumer requests values, not when the generator expression is created.
02What four steps make the practice loop reliable?
Predict the behavior, make one coherent change, run it, and retain a check that detects regression.
Exercise
Practice challenge
Normalize a list of names, discard blanks, deduplicate case-insensitively, and produce a sorted display list using readable staged transformations.
Requirements
- The successful path produces the documented result
- At least one boundary or invalid case is handled deliberately
- Calculation or domain logic is separated from console interaction
Optional extension: Add one automated regression check for the most important rule.
Open in Python compilerLesson checkpoint
One small step locks it in
Mark this lesson complete, then keep the momentum going.
Clear up the details
Frequently asked questions
Is declarative iteration only important in large programs?
No. Small programs reveal the same rules with less noise, and learning the rule early prevents fragile habits from becoming architecture.
Should I memorize every API used here?
No. Memorize the mental model and how to verify behavior. Use documentation for exact names and parameters when needed.
How do I know the exercise is finished?
Meet every success criterion, test at least one boundary or failure case, and explain why the output follows from the code.