Lesson 8: List Comprehensions & Generators
Python's list comprehensions are one of its most powerful features — they let you create, filter, and transform lists in a single readable line. Generators take this further, producing values lazily to save memory.
Key Concepts
List Comprehensions
[expression for item in iterable if condition]
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
up_scores = [s*1.1 for s in scores if s < 90]
Dict & Set Comprehensions
{k: v for k, v in pairs} # dict comprehension
{x**2 for x in range(5)} # set comprehension
word_lengths = {word: len(word) for word in words}
Generators
(x**2 for x in range(1000000)) # generator, not list!
Generators produce values one at a time — never stores the whole list. Use next() or a for loop. Ideal for large datasets.
zip() and enumerate()
for i, (name, score) in enumerate(zip(names, scores)):
print(i, name, score)
zip() pairs up multiple iterables. enumerate() adds an index. Both work perfectly with comprehensions.
✅ Check Your Understanding
1. [x*2 for x in range(5)] produces:
2. What is the key difference between a list comprehension and a generator?
3. What does zip(['a','b'], [1,2]) produce?