CodingNeed.
Fresher · Language concepts

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 * value
Strong 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 * value

Common traps

  • Generators are consumed; a second pass does not restart them.
  • State assumptions and justify trade-offs rather than memorizing a single answer.
Practise in the workspace →

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.