Under The Hood
backend python CPython 3.12+

Python generators: lazy memory efficiency

Last updated
Prerequisites:
Python functions and iteration basics
Understanding of lists vs iterators
  • python
  • generators
  • memory
  • lazy-evaluation
  • iterators
  • yield

Read at your depth

The practical view

A generator is a function with yield instead of return: def evens(n): for i in range(n): if i % 2 == 0: yield i. Calling it returns a generator object (an iterator), not the values. Each next(gen) resumes execution from the previous yield until the next yield or StopIteration. for x in evens(10) drives it automatically. The memory win: a list of a million numbers holds a million int objects; a generator computes them on demand. Use generators for streaming large data (files, logs, API pagination), infinite sequences, and pipelines (gen1 | gen2 via yield from or chained loops).

Legacy vs modern

Building a list vs streaming with a generator

A list materializes every value in memory; a generator computes one value at a time, bounding memory to the working set.

before → after
Materialized list
lines = [line.strip() for line in open('big.log')]
unique = {line for line in lines}
Streaming generator
unique = set()
total = 0
for line in open('big.log'):   # iterating a file IS a generator
    unique.add(line.strip())
    total += 1

Interview gotchas

Under The Hood — a multi-depth technical interview hub.

Press ⌘ K to search.