Comprehensions
Building lists, sets, and dicts in one line.
4 minute read
Big idea
A comprehension builds a new list (or set, or dict) from an existing sequence in one readable line: [expression for item in sequence if condition].
From loop to comprehension
This loop builds a list of squares:
squares = []
for n in range(1, 6):
squares.append(n * n)
The comprehension says the same thing in one line:
squares = [n * n for n in range(1, 6)]
print(squares)output
[1, 4, 9, 16, 25]Run and edit it in the app.
Read it as: "n × n, for each n in 1 to 5".
Filtering with if
Add if at the end to keep only some items:
nums = [4, 7, 10, 13, 16]
evens = [n for n in nums if n % 2 == 0]
halves = [n // 2 for n in nums if n > 8]
print(evens)
print(halves)What does it print? Show the answer
[4, 10, 16]
[5, 6, 8]Run and edit it in the app.
Working with strings
raw = [" ada ", "GRACE", "linus "]
clean = [name.strip().title() for name in raw]
print(clean)
lengths = [len(name) for name in clean]
print(lengths)output
['Ada', 'Grace', 'Linus']
[3, 5, 5]Run and edit it in the app.
Set and dict comprehensions
Curly braces make a set; key: value makes a dict:
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
first_letters = {w[0] for w in words}
print(sorted(first_letters))
lengths = {w: len(w) for w in words if w.startswith("b")}
print(lengths)output
['a', 'b', 'c']
{'banana': 6, 'blueberry': 9}Run and edit it in the app.
Keep them readable
A comprehension should fit comfortably on one line. If you need nested loops, several conditions, or a print inside, write a normal for loop — clarity beats cleverness.
words = ["hi", "hello", "yo", "world", "hey"]
long_words = [w for w in words if len(w) < 3]
print(long_words)output
['hello', 'world']Run and edit it in the app.
What is [x * 2 for x in range(4) if x != 2]?
Watch it
Think of it like
An instruction to a helper: "for every apple in the basket, if it isn't bruised, slice it and put it on the plate." One sentence, and you get a plate of slices.
Key terms
- List comprehension —
[expr for x in seq if cond]: builds a list in one line. - Filter — The
ifpart, which keeps only some items. - Set / dict comprehension — The same idea with
{x ...}or{k: v ...}.
Check yourself
What is [c.upper() for c in "ab"]?
Where does the filtering if go in a comprehension?
When should you use a normal loop instead?