Beyond lists
Programs constantly need lookup tables (name → value) and deduplicated collections, and building them item by item is boilerplate. Dict and set comprehensions produce both in one line from anything you can loop over.
You built dictionaries key by key in Python for Beginners: d[key] = value inside a loop. Comprehensions cover that too. Swap the square brackets for curly braces and write a key: value pair up front:
lengths = {word: len(word) for word in words}Drop the colon and you get a set comprehension instead, a collection of unique values with no order:
firsts = {word[0] for word in words}One symbol changes the container:
| Brackets | Front part | Builds |
|---|---|---|
[expr ...] | one value | list |
{k: v ...} | pair with colon | dict |
{expr ...} | one value | set |
Code exercise · python
Run this program. Note the set prints only unique first letters, and we sort it before printing so the output is stable.
Code exercise · python
Your turn. Build with_tax, a dict mapping each product name to its price times 1.1, rounded to 2 decimals with round(value, 2). Loop over prices.items() inside the comprehension, then print the dict.
Nested comprehensions
A comprehension can hold two for clauses. They read exactly like nested loops, outer loop first:
pairs = [(x, y) for x in [1, 2] for y in ["a", "b"]] # [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
The classic use is flattening a list of lists into one flat list:
grid = [[1, 2], [3, 4], [5, 6]] flat = [cell for row in grid for cell in row] # [1, 2, 3, 4, 5, 6]
Read it as: for each row in grid, for each cell in that row, take cell. If you need three levels or heavy logic, go back to real loops. Readability wins.
Code exercise · python
Your turn. Flatten `grid` into a single list called `flat` using one comprehension with two for clauses, then print it.
Quiz
Which comprehension builds a dict mapping each number to its double, for nums = [1, 2, 3]?
Problem
You run {len(w) for w in ["hi", "to", "sun", "me"]}. How many items are in the resulting set? Answer with a single number.