How does a generator expression differ from a list comprehension, and when does that difference matter?
Answer
A list comprehension `[x * 2 for x in data]` builds the entire list in memory immediately. A generator expression `(x * 2 for x in data)` builds a lazy iterator that produces one value at a time on demand and is never materialized as a full sequence. The difference matters for large or unbounded data sources: a generator avoids materializing the whole result sequence at once, which typically keeps its own memory footprint far flatter than a list comprehension's, though total memory use still depends on what the surrounding code does with each value and whether any generator state accumulates. A generator can also only be iterated once and does not support indexing or `len()`.
Strong answer includes
- list comprehension is eager, generator expression is lazy
- avoids materializing the whole result sequence, typically much flatter memory than a list
- generators are single-use, no indexing or len
Practical example
Run the code to see the result.
The comprehension materializes all five values immediately. The generator produces values only when consumed and remembers where it paused between next() calls.
Expected result: [0, 1, 4, 9, 16], then 0, then 1, then [4, 9, 16].