Level: Intermediate | Prerequisite: Week 1 (Advanced Functions)
Learning Goals
- Write list, dictionary, and set comprehensions
- Understand generator functions and expressions
- Write memory-efficient code
1. List Comprehensions
[expression for variable in sequence if condition] Create a list in one line.
#Existing
squares = []
for x in range(10):
squares.append(x * x)
#Comprehension
squares = [x * x for x in range(10)]
Add conditions:
even_sq = [x * x for x in range(10) if x % 2 == 0]
# [0, 4, 16, 36, 64]
Nested:
pairs = [(i, j) for i in range(3) for j in range(3) if i != j]
2. Dictionary and Set Comprehensions
words = ["apple", "banana", "cherry"]
#Dictionary: {key: value for ...}
length_map = {w: len(w) for w in words}
# {'apple': 5, 'banana': 6, 'cherry': 6}
#Set: {expression for ...}
unique_lens = {len(w) for w in words}
# {5, 6}
3. Generator Functions
return instead of yield. Produce results one by one as needed, not all at once.
def fib(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
for x in fib(10):
print(x, end=" ") # 0 1 1 2 3 5 8 13 21 34
If you want to see them all at once as a list, use list(fib(10)).
4. Generator Expressions
Use parentheses instead of brackets → save memory.
#List comprehension (eats up all the memory)
total = sum([x * x for x in range(1_000_000)])
#Generator expression (one at a time)
total = sum(x * x for x in range(1_000_000))
5. When to use which?
| Situation | Tool |
|---|---|
| Small data + need index | List comprehension |
| Large data + single pass | Generator |
| Key-value mapping | Dictionary comprehension |
| Remove duplicates | Set comprehension |
Key Examples (examples/)
| File | Content |
|---|---|
01_list_comp.py |
List comprehension |
02_dict_set_comp.py |
Dictionary/Set |
03_generator.py |
Generator function |
04_generator_expr.py |
Generator expression (compare memory) |
⚠️ Common Mistakes
- Comprehension is too long and complicated — if readability drops, just use a for loop
- Iterate the generator twice — once fully iterated, it will be empty. Needs to be called again.
- If
yieldis anywhere in the function, the entire function is a generator — cannot return normal values withreturn
❓ FAQ
Q1. Are comprehensions always faster than for loops? A. Usually slightly faster. The biggest difference is readability and expression of intent.
Q2. Can we know the length of a generator? A. No. If you need the length, convert it to a list (memory usage).
Q3. Can there be multiple yields? A. Yes. Each time it is called, it executes up to the next yield.
📝 Exercises (exercises/)
exercise1.md— primes from 1 to 100 (comprehension)exercise2.md— mapping word lengthsexercise3.md— large file line-by-line generator
Next Week
Week 3. Modules and Packages