List and Dictionary Comprehensions
Transform and filter collections cleanly in a single readable line.
Learning objectives
- Write list comprehensions [expr for item in iterable if condition]
- Use enumerate() to track indices and zip() to pair iterables
Lesson material
Comprehensions
Comprehensions replace verbose multi-line loops with compact expressions.
Example code
# Filter and square even numbers
numbers = [1, 2, 3, 4, 5, 6]
squares = [x**2 for x in numbers if x % 2 == 0]
print("Even squares:", squares)
# Dictionary comprehension
names = ["alice", "bob"]
len_map = {name.title(): len(name) for name in names}
print("Length map:", len_map)
Practice exercise: Filter Even Squares
Use a list comprehension to square all odd numbers in list `[1, 2, 3, 4, 5]`. Print the resulting list.
Test yourself with the Module 11: Pythonic Programming & Comprehensions quiz →