Comprehensions & Generators
List, dict, set comprehensions, generator expressions, map/filter
Skills taught: python.list-comprehension, python.dict-comprehension, python.generator, python.map-filter
List and set comprehensions
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Basic list comprehension
squares = [n**2 for n in numbers]
print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# With filter condition
evens = [n for n in numbers if n % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]
# Transform + filter
even_squares = [n**2 for n in numbers if n % 2 == 0]
print(even_squares) # [4, 16, 36, 64, 100]
# Ternary in expression (transform, not filter)
signs = ['pos' if n > 0 else 'neg' for n in [-1, 2, -3, 4]]
print(signs) # ['neg', 'pos', 'neg', 'pos']
# Flatten 2D list
matrix = [[1,2,3],[4,5,6],[7,8,9]]
flat = [n for row in matrix for n in row]
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Set comprehension — unique values only
words = ['hello','world','hello','python','world']
unique_upper = {w.upper() for w in words}
print(unique_upper) # {'HELLO', 'WORLD', 'PYTHON'}
Dict comprehensions and generators
# Dict comprehension
names = ['Alice', 'Bob', 'Charlie']
scores = [95, 82, 78]
# zip + dict comprehension
score_map = {name: score for name, score in zip(names, scores)}
print(score_map) # {'Alice': 95, 'Bob': 82, 'Charlie': 78}
# Invert a dict
original = {'a': 1, 'b': 2, 'c': 3}
inverted = {v: k for k, v in original.items()}
print(inverted) # {1: 'a', 2: 'b', 3: 'c'}
# Filter a dict (keep high scorers)
high = {name: score for name, score in score_map.items() if score > 80}
print(high) # {'Alice': 95, 'Bob': 82}
# Generator expression — lazy, memory-efficient
total = sum(n**2 for n in range(1, 1001)) # no list created!
print(total) # 333833500
big_nums = (n for n in range(10_000_000) if n % 1_000_000 == 0)
for n in big_nums:
print(n) # 0, 1000000, 2000000, ... (lazy — no 10M list)
# any() / all() with generators — short-circuit
nums = [2, 4, 6, 8, 9]
print(any(n % 2 != 0 for n in nums)) # True (9 is odd)
print(all(n > 0 for n in nums)) # True
map, filter, and zip
nums = [1, 2, 3, 4, 5]
# map() — apply function to each item
squared = list(map(lambda x: x**2, nums))
print(squared) # [1, 4, 9, 16, 25]
# (comprehension equivalent: [x**2 for x in nums])
# filter() — keep items where function returns True
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # [2, 4]
# zip() — pair up iterables
names = ['Alice', 'Bob', 'Charlie']
scores = [95, 82, 78]
pairs = list(zip(names, scores))
print(pairs) # [('Alice', 95), ('Bob', 82), ('Charlie', 78)]
# zip to build dict
d = dict(zip(names, scores))
# zip with unequal lengths — stops at shortest
zip_short = list(zip([1,2,3], ['a','b']))
print(zip_short) # [(1,'a'), (2,'b')] — 3 dropped!
# sorted with key
people = [{'name':'Bob','age':30},{'name':'Alice','age':25}]
by_age = sorted(people, key=lambda p: p['age'])
by_name = sorted(people, key=lambda p: p['name'])
Frequently Asked Questions
Should I use map/filter or comprehensions?
Comprehensions are generally preferred in Python — they're more readable. Use map() when you already have a named function: map(str, numbers) is cleaner than [str(n) for n in numbers]. Use filter() similarly. For anonymous transformations, comprehensions win: [x**2 for x in nums] vs map(lambda x: x**2, nums).
How do I write a generator function?
Use yield instead of return: def count_up(n): for i in range(n): yield i. Calling count_up(5) returns a generator object. Each call to next() runs until the next yield. Use in for loops, or list() to consume all values.