[n * 2 for n in nums]: first what to keep, then where it comes from.
Filter
An if at the end keeps only some items: [n for n in nums if n > 0].
Choose
a if test else b at the front picks a value for every item.
Dicts and sets
Curly braces make a set, or with key: value a dictionary.
Comprehensions everywhere
Whenever data is cleaned up or reshaped, a comprehension is often doing the work.
Clean up inputStrip the spaces from every name a form sent in.
PlaylistsKeep only the songs shorter than four minutes.
Game boards[[0] * 3 for row in range(3)] makes an empty 3 by 3 grid.
Sale prices{item: price * 0.9 for item, price in ...} builds a new price list.
Part 1 of 8
Tap any part of the code below, or press Next.1 of 8 explored
new list:The comprehension builds a brand new list and stores it here.
Example 1 of 6Loop to one line
Both versions build the same list. The comprehension says it in one line.
Your turn: Change both versions so they add 10 to each number.
Python
1
2
3
4
5
6nums = [1, 2, 3, 4]
doubled = []
for n in nums:
doubled.append(n *2)
print(doubled)
print([n *2for n in nums])
Output
Press Run to see what it prints.
Ready. Press Step to run the first line.
1prices = [4, 12, 7, 20]
2cheap = [p for p in prices if p <10]
3labels = ["cheap"if p <10else"pricey"for p in prices]
4total =sum(cheap)
5print(cheap, total)
6print(labels)
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Question 1 of 6
1.Squares from a range:
print([i * i for i inrange(4)])
2.Looping over a word:
print([c.upper() for c in"hey"])
3.How many items survive?
nums = [5, -2, 8, -1]
print(len([n for n in nums if n >0]))
4.Repeats in a set comprehension:
print(len({w for w in ["a", "b", "a"]}))
5.What does the dictionary hold?
print({n: n *10for n in [1, 2]})
6.Flattening rows:
rows = [[1, 2], [3]]
print([x for row in rows for x in row])
0 of 6 answered
Misconception 1 of 4
Read the notesNotesOpenClose
From loop to comprehension
Here is a pattern you have written many times:
Try it 1: edit me, then Run
1
2
3
4
5numbers = [1, 2, 3, 4]
squares = []
for n in numbers:
squares.append(n * n)
print(squares) # [1, 4, 9, 16]
Output
Press Run to see what it prints.
A list comprehension builds the same list in one expression:
Try it 2: edit me, then Run
1squares = [n * n for n in numbers]
Output
Press Run to see what it prints.
Read it from the middle outwards: for each n in numbers, put n * n in the new list. The square brackets say the result is a list. The part before for is the expression that produces each new item, and the for clause works exactly like the loop it replaces. The original list is not changed; a brand new list is created.
The loop variable n only exists inside the comprehension. After the line runs, n is not defined outside it, unlike the variable of a normal for loop.
Keeping some items: the if clause
Add if at the end to keep only items that pass a test:
Try it 3: edit me, then Run
1
2
3scores = [45, 82, 67, 30, 91]
passed = [s for s in scores if s >=50]
print(passed) # [82, 67, 91]
Output
Press Run to see what it prints.
The filter runs first for each item; only items where it is true reach the expression. You can transform and filter together: [s + 5 for s in scores if s < 50] adds five points to the failing scores only.
Choosing a value: the conditional expression
Sometimes you want to keep every item but change it in one of two ways. That needs a conditional expression, a if condition else b, placed before the for:
Try it 4: edit me, then Run
1
2labels = ["pass"if s >=50else"fail"for s in scores]
print(labels) # ['fail', 'pass', 'pass', 'fail', 'pass']
Output
Press Run to see what it prints.
The position tells you which job it is doing. An if at the end filters, so the new list can be shorter. An if ... else at the front chooses a value, so the new list always has the same length. Writing [s for s in scores if s >= 50 else 0] is a syntax error, because a filter has no else.
Dictionary and set comprehensions
Curly braces with a key: value pair build a dictionary:
Try it 5: edit me, then Run
1
2
3
4
5
6names = ["ana", "ben", "cy"]
lengths = {name: len(name) for name in names}
print(lengths) # {'ana': 3, 'ben': 3, 'cy': 2}
prices = {"tea": 2.5, "cake": 4.0}
with_tax = {item: round(p *1.2, 2) for item, p in prices.items()}
Output
Press Run to see what it prints.
Curly braces with a single expression build a set, which removes duplicates:
Try it 6: edit me, then Run
1
2
3words = ["Apple", "apple", "PEAR", "pear", "fig"]
unique = {w.lower() for w in words}
print(sorted(unique)) # ['apple', 'fig', 'pear']
Output
Press Run to see what it prints.
A set has no fixed order, so sort it before printing when the order matters. Note that {} on its own is an empty dictionary, not an empty set.
Two for clauses
A comprehension can contain more than one for. They run in the same order as nested loops written out top to bottom:
Try it 7: edit me, then Run
1
2
3
4sizes = ["S", "M"]
colours = ["red", "blue"]
options = [f"{c}-{s}"for c in colours for s in sizes]
print(options) # ['red-S', 'red-M', 'blue-S', 'blue-M']
Output
Press Run to see what it prints.
The first for is the outer loop and the second is the inner loop. The same idea flattens a list of lists: [x for row in grid for x in row].
Comprehension or map and filter?
The previous lesson showed map and filter. A comprehension usually says the same thing more directly, with no lambda and no list() call:
Try it 8: edit me, then Run
1
2list(map(lambda n: n *2, numbers)) # map version
[n *2for n in numbers] # comprehension version
Output
Press Run to see what it prints.
Most Python programmers reach for the comprehension. map still reads well when you already have a named function, as in list(map(str, numbers)).
Reading someone else's comprehension
When you meet a comprehension in another person's code, read it in three steps. First find the for clause and ask what is being looped over. Next look at the end for an if that filters. Finally read the expression at the front to see what each new item becomes. Saying it aloud helps: [p.title() for p in pets if p] is "the title-cased version of each pet, skipping blanks". Good names matter here too: [order.total for order in orders] explains itself, while [x.t for x in o] does not.
When a loop is better
Comprehensions are for building a collection. If you only want side effects, such as printing each item, use a normal loop: [print(x) for x in items] works but builds a useless list of None values. If a comprehension needs two conditions, nested conditional expressions and two for clauses, it has stopped being readable. Split it into a loop or a helper function. A good rule is that a comprehension should fit on one line and be explainable in one sentence.
syntax.py
1
2
3
4
5
6[expr for x in items] # transform every item
[expr for x in items if test] # keep items that pass
[a if test else b for x in items] # choose a value for every item
{k: v for k, v in pairs} # dictionary comprehension
{expr for x in items} # set comprehension
[x for row in grid for x in row] # two for clauses, outer first
Output
Press Run to see what it prints.
Example 1 of 2
Preparing a price list
Beginner
A cafe stores prices without tax. Make a list of prices with 20% tax, a list of only the items under 3.00 before tax, and a dictionary from item to its taxed price.
Python
1
2
3
4
5
6
7
8
9menu = [("tea", 2.2), ("cake", 3.5), ("toast", 1.8), ("soup", 4.5)]
taxed = [round(price *1.2, 2) for name, price in menu]
cheap = [name for name, price in menu if price <3]
price_of = {name: round(price *1.2, 2) for name, price in menu}
print(taxed)
print(cheap)
print(price_of["soup"])
Output
Press Run to see what it prints.
Predict first
How it works(open after your guess)
Each tuple is unpacked into name, price in the for clause, just as in a normal loop. The first comprehension keeps every item, the second filters with an if at the end, and the third uses curly braces with a key and a value to build a dictionary.
Grading a class
Beginner
Turn a list of marks into grade labels, count how many students passed, and list the distinct grades in alphabetical order.
Python
1
2
3
4
5
6
7
8
9marks = [72, 48, 91, 55, 38, 91]
grades = ["A"if m >=85else"B"if m >=60else"C"if m >=50else"F"for m in marks]
passed =len([m for m in marks if m >=50])
distinct =sorted({g for g in grades})
print(grades)
print("Passed:", passed)
print("Grades used:", distinct)
Output
Press Run to see what it prints.
Predict first
How it works(open after your guess)
The grade line chains conditional expressions; it is about as long as a comprehension should get, and a helper function would be a fair alternative. The filter comprehension counts passes, and the set comprehension removes the duplicate grades before sorting.
Pitfall 1 of 3
Putting else on a filter
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
Buggy code: run it
1
2scores = [40, 70]
result = [s for s in scores if s >=50else0]
Output
Press Run to see what it prints.
Show what goes wrong and the fixWhat goes wrong and the fix
What happens
SyntaxError: invalid syntax
Write this instead
scores = [40, 70]
result = [s if s >=50else0for s in scores]
Why it happens
An if at the end filters and cannot have an else. A choice between two values must come before the for.
Expecting an empty-brace set
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
Buggy code: run it
1
2seen = {}
seen.add('a')
Output
Press Run to see what it prints.
Show what goes wrong and the fixWhat goes wrong and the fix
What happens
AttributeError: 'dict' object has no attribute 'add'
Write this instead
seen =set()
seen.add('a')
Why it happens
Empty curly braces make an empty dictionary. Only braces with items, or a set comprehension, make a set.
Using a comprehension only for printing
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
Buggy code: run it
1
2names = ['Ana', 'Ben']
[print(n) for n in names]
Output
Press Run to see what it prints.
Show what goes wrong and the fixWhat goes wrong and the fix
What happens
Prints the names, but also builds a pointless list [None, None]
Write this instead
names = ['Ana', 'Ben']
for n in names:
print(n)
Why it happens
A comprehension always builds a collection. print returns None, so the list fills with None values that nobody uses.
Tidying survey answers
Market research
An online survey collects favourite fruit as free text. Before counting, the answers are cleaned, blanks dropped and a tally built per fruit.
Why Python fits
The filter if a.strip() drops answers that are empty or only spaces, since an empty string is false. The dictionary comprehension loops over the sorted distinct fruits so the tally prints in a stable order.
Python
1
2
3
4
5
6answers = [" Mango", "apple ", "", "APPLE", "mango", " ", "Kiwi"]
clean = [a.strip().lower() for a in answers if a.strip()]
tally = {fruit: clean.count(fruit) for fruit insorted(set(clean))}
print(clean)
print(tally)
Output
Press Run to see what it prints.
Tick each one you could explain to a friend.
0 of 5
Is a comprehension faster than a loop?
Often a little, because Python runs it in a tighter internal loop. The real benefit is clarity; never squeeze unreadable logic into one just for speed.
What happens if I use round brackets?
(n * n for n in numbers) makes a generator expression, a lazy iterator like map. It is handy inside sum or max, and the Python in Depth course covers it fully.
Can a comprehension change the list it reads?
It should not. It reads the source and builds a separate result. Changing the source while looping over it leads to confusing bugs.