01 / 20

Generator vs. List
Comprehensions

Understand when to use generator expressions for lazy evaluation and when list comprehensions build everything at once: the trade-offs that shape memory, speed, and Pythonic style.

Python

What Is a List Comprehension?

A list comprehension is a concise syntax that builds an entire list in memory in one expression. It evaluates every element immediately and stores them all.

squares = [x**2 for x in range(10)] # Result: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

What Is a Generator Expression?

A generator expression looks almost identical but uses parentheses instead of brackets. It produces values one at a time, on demand — never holding the whole sequence in memory.

squares = (x**2 for x in range(10)) # Result: <generator object <genexpr> at 0x...>

Why Does This Matter?

Memory
A list of 10 million items can consume hundreds of MB. A generator uses almost none.
Speed
If you only need the first match, a generator stops early. A list computes everything first.
Pipelines
Generators chain together into data pipelines that process streams without buffering.

The Core Rule

List Comprehension [ expr for x in iter ] 0 1 4 ... ALL values in memory Indexable, reusable, len() works Generator Expression ( expr for x in iter ) next? ONE value at a time Single pass, low memory, no len() or index

Memory Model Visualised

Memory Number of elements (n) 100 10K 1M 10M List Gen O(n) memory O(1) memory

Key Distinction: Eager vs. Lazy

List Comprehension Generator Expression
Syntax [ expr for x in iter ] ( expr for x in iter )
Evaluation Eager: all at once Lazy: on demand
Memory \( O(n) \) \( O(1) \)
Reusable? Yes, iterate many times No, single pass only
Supports len()? Yes No
Supports indexing? Yes: lst[3] No

When to Use Each

Use a List When:
You need to index, slice, iterate multiple times, or check len(). The dataset is small enough to fit comfortably in memory.
Use a Generator When:
You only need a single pass, the data is large or infinite, or you are feeding into sum(), any(), min(), or another function that consumes iterables.

How to Decide: Step by Step

1
Ask: "Will I iterate more than once?" If yes, you need a list.
2
Ask: "Do I need len(), indexing, or slicing?" If yes, you need a list.
3
Ask: "Is the dataset huge or potentially infinite?" If yes, prefer a generator to avoid memory overflow.
4
Ask: "Am I passing directly into sum(), min(), max(), any(), or join()?" If yes, a generator is cleaner and saves memory.
5
Default: For small, finite, reused data, a list comprehension is fine. Otherwise, reach for a generator.

Example 1: Summing Squares

Goal: compute the sum of all \( x^2 \) for \( x \) from 1 to 1,000,000.

List approach
total = sum([x**2 for x in range(1_000_000)]) # Builds a 1M-item list first # ~8 MB of memory
Generator approach
total = sum(x**2 for x in range(1_000_000)) # No intermediate list # ~0 extra memory

Example 2: Filtering Data

Goal: find the first filename ending in .py from a large directory listing.

files = ["readme.md", "app.py", "test.py", "logo.png", ...] # Generator: stops as soon as first match is found first_py = next( f for f in files if f.endswith(".py") ) # first_py = "app.py"

Example 3: Chaining Generators

Goal: read a log file, extract lines with "ERROR", and count them — without loading the entire file into memory.

with open("server.log") as fh: errors = ( line for line in fh if "ERROR" in line ) count = sum(1 for _ in errors) print(count) # e.g. 4217

The Exhaustion Trap

Generators are single-use. Once consumed, they are empty forever. This catches many beginners off-guard.

gen = (x**2 for x in range(5)) print(list(gen)) # [0, 1, 4, 9, 16] print(list(gen)) # [] ← EMPTY!

Syntax Shortcut: No Double Parens

When a generator expression is the only argument to a function, Python lets you omit the extra parentheses.

Redundant
sum((x**2 for x in data)) # Works, but extra parens
Pythonic
sum(x**2 for x in data) # Clean, idiomatic

Common Mistakes

✕ Reusing an Exhausted Generator
Iterating a generator twice returns nothing the second time. Always recreate it or convert to a list if multi-pass is needed.
✕ Calling len() on a Generator
Generators have no length. len(gen) raises a TypeError. Use sum(1 for _ in gen) instead — but note this exhausts it.
✕ Indexing a Generator
gen[3] raises a TypeError. Generators do not support random access. Use next() or itertools.islice().

Summary Comparison

[ ] List Comp. ( ) Generator
Returns list object generator object
Memory \( O(n) \) \( O(1) \)
Speed (small n) Slightly faster Slightly slower
Speed (large n) Allocation overhead Wins if single-pass
Reusable ✓ ✕
Supports len() ✓ ✕
Supports indexing ✓ ✕
Best for Small, reused data Large/infinite streams

Question 1 of 5

What is the primary advantage of a generator expression over a list comprehension?

Question 2 of 5

What does the following code print on the second call?

g = (x * 2 for x in range(3)) print(list(g)) # First call print(list(g)) # Second call

Question 3 of 5

Which approach is most Pythonic for computing the sum of squares from 1 to \( n \)?

Question 4 of 5

You need to iterate over the results three separate times and also call len() on the result. Which should you use?

Question 5 of 5

You are processing a 10 GB log file line by line and only need to count lines containing "ERROR". What is the best strategy?