List Comprehensions and Generators: Lazy Data in Python
Build transformed and filtered lists in one readable expression, and use generator expressions to process huge files without blowing up RAM.
You'll learn how list comprehensions condense for + .append() loops into one clean line, when to avoid them, and how swapping [] for () turns a list into a memory-saving lazy generator. Assumes comfort with Python lists and for loops.
1. Transforming lists without the boilerplate
Every Python developer writes this pattern fifty times: make an empty list, loop over items, check an if, and .append() the transformed result.
A list comprehension collapses those four lines into one expression inside square brackets []:
nums = [1, 2, 3, 4, 5, 6]
even_squares = [n * n for n in nums if n % 2 == 0]
print(even_squares)[4, 16, 36]Read it in English: "Give me n * n for each n in nums, keeping only the ones where n % 2 == 0."
2. Don't get too clever with them
Comprehensions are great for simple one-step transforms and filters. The moment you nest two loops or cram three if/else conditions inside one line, write a normal for loop. Future-you reading that code at 11 p.m. deserves mercy.
Also, never use a comprehension just for side effects like [print(x) for x in items]—it builds a useless list of [None, None, ...] just to throw it away.
Write a comprehension that strips whitespace from [" go ", " python ", "web"] -> ["go", "python", "web"].
3. Generators: computing one item at a time
Suppose you want the sum of squares from 1 to 10,000,000.
A list [n * n for n in range(10_000_000)] allocates hundreds of megabytes of RAM to store all 10 million numbers at once, only for sum(...) to add them up and throw the list away.
Swap the square brackets [] for parentheses () to create a generator expression:
total = sum(n * n for n in range(10_000_000))
print(total)333333283333335000000A generator is lazy: it produces one number at a time, hands it to sum(), and forgets it immediately—using almost zero memory.
You can also write multi-line generators with yield inside a function:
def read_non_empty(lines):
for line in lines:
cleaned = line.strip()
if cleaned:
yield cleanedOne gotcha: a generator is single-use. Once you loop through it once, it is exhausted (empty) unless you call the generator function again.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Looped over a generator twice | Second loop produces nothing (already exhausted) | Convert to list(gen) if you need to iterate multiple times |
Put if ... else at the end of a comprehension | SyntaxError | Filter if goes at the end; ternary a if cond else b goes before for |
[print(x) for x in items] | Allocates a wasted list of Nones | Use a plain for loop for side effects |
Practice
- What is the memory difference between
sum([x for x in range(1_000_000)])andsum(x for x in range(1_000_000))?
Answer: The first builds a 1,000,000-element list in memory before summing; the second streams one number at a time using constant memory.
What you learned
- List comprehensions (
[expr for x in items if cond]) replace simple append loops cleanly. - Generator expressions (
(expr for x in items)) andyieldfunctions compute values lazily one at a time. - Generators are single-use—once consumed, they are empty.