Generators vs. Lists
Compare a list comprehension with a generator when processing a large file. Explain iteration, laziness, and resource lifetime.
Examples
Compare approaches
Baseline approach
Begin by explaining the core mechanism, stating assumptions, and walking through one concrete example.
Time: Depends on design · Space: Depends on design
def squares(values):
for value in values:
yield value * valueStrong answer
A generator evaluates lazily and holds its current state. A list eagerly materializes results. Both perform O(n) total work; the generator needs O(1) auxiliary state for this example.
Time: O(n) total · Space: O(1) auxiliary
def squares(values):
for value in values:
yield value * valueCommon traps
- Generators are consumed; a second pass does not restart them.
- State assumptions and justify trade-offs rather than memorizing a single answer.