Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Data types & structuresMiddleVery commonPractical

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

Eager list versus lazy generator
Python
editable · browser sandbox
Result
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].

#comprehensions#generators#performance

Sources

The Python TutorialPython Software Foundation · Baseline syntax, control flow, functions and module basicsitertools — Functions creating iterators for efficient loopingPython Software Foundation · Lazy iterator composition and memory-efficient looping patterns