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.
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.
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.
Why Does This Matter?
The Core Rule
Memory Model Visualised
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
How to Decide: Step by Step
Example 1: Summing Squares
Goal: compute the sum of all \( x^2 \) for \( x \) from 1 to 1,000,000.
Example 2: Filtering Data
Goal: find the first filename ending in .py from a large directory listing.
Example 3: Chaining Generators
Goal: read a log file, extract lines with "ERROR", and count them — without loading the entire file into memory.
The Exhaustion Trap
Generators are single-use. Once consumed, they are empty forever. This catches many beginners off-guard.
Syntax Shortcut: No Double Parens
When a generator expression is the only argument to a function, Python lets you omit the extra parentheses.
Common Mistakes
len(gen) raises a TypeError. Use sum(1 for _ in gen) instead — but note this exhausts it.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?
list(g) exhausts all values. The second call finds no remaining items and returns an empty list [].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?
sum(1 for line in fh if "ERROR" in line).