Comprehensions
squares = [n * n for n in range(1, 5)]Take each n from range(1, 5) and put n * n into the new list.
1Level 1 · BasicsBasics
You'll often build a new list by looping over another one. A comprehension does that in a single, readable line. It's one of the things that makes Python code short and expressive.
From loop to comprehension
Here's the long way to make a list of squares:
squares = []
for n in range(1, 6):
squares.append(n * n)
And the same thing as a list comprehension:
squares = [n * n for n in range(1, 6)] # [1, 4, 9, 16, 25]
Read it left to right: "make n * n for each n in range(1, 6)". The square brackets mean the result is a list.
Filtering with if
Add an if at the end to keep only some items:
evens = [n for n in range(20) if n % 2 == 0] long_words = [w for w in words if len(w) > 4]
Choosing a value with if/else
To transform every item in one of two ways, put the if/else at the front:
labels = ["even" if n % 2 == 0 else "odd" for n in nums]
Remember the difference: if at the end filters, if/else at the front chooses.
Dictionary and set comprehensions
lengths = {w: len(w) for w in words} # dict
initials = {name[0] for name in names} # set
Generator expressions
With round brackets inside a function call you don't even build a list: sum(n * n for n in range(1000)). This saves memory for large data.
Keep them readable
Comprehensions are great for simple transformations. If you need several conditions or nested loops, a normal for loop is often clearer, and clear code beats clever code.
Key points:[expr for x in items]builds a list; addif condat the end to filter; puta if cond else bat the front to choose; use{k: v for ...}for dictionaries.
See it in actionOne line builds a whole list
Each comprehension makes a complete new list (or dictionary) in a single step.
Try it yourselfExample 1: Loop vs comprehension
Both build exactly the same list.
Output appears hereSquares in one line
Fill the blanks so the list holds the squares of 1 to 5: [1, 4, 9, 16, 25].
squares = [n 2 n in range(1, 6)] print(squares)
Example 2: Filtering
The if at the end keeps only the items you want.
Output appears hereOnly long words
Fill the blank so only words longer than 3 letters are kept: ['apple', 'kiwis'].
words = ["fig", "apple", "kiwis", "pea"] print([w for w in words len(w) > 3])
Example 3: Choosing with if/else
Every item stays, but each is turned into one of two labels.
Output appears hereif/else in the wrong place
This should label each number: ['odd', 'even', 'odd'] for [1, 2, 3]. Python reports an error. Fix the order.
Example 4: Dictionary and set comprehensions
Curly braces with key: value make a dictionary; without a colon they make a set.
Output appears hereShout the names
Using a list comprehension, turn names = ["mim", "joy", "tara"] into capitals and print ['MIM', 'JOY', 'TARA'].
Name lengths
Use a dictionary comprehension to map each word to its length. For ["sun", "moon"] print {'sun': 3, 'moon': 4}.
2Level 2 · IntermediateNested comprehensions
Two for clauses
[(r, c) for r in range(2) for c in range(3)] reads like two nested loops, outer first. Use it for pairs, combinations and flattening.
Flattening
[x for row in grid for x in row] turns a list of lists into one list.
Comprehension inside a comprehension
[[r * c for c in range(1, 4)] for r in range(1, 4)] builds a 2-D table. The inner one makes a row; the outer repeats it.
Transposing
[list(col) for col in zip(*matrix)] turns rows into columns.
See it in actionFlattening step by step
Watch row and x change; x moves fastest, like an inner loop.
Example 5: Tables, pairs and transposing
Change the ranges and see the shapes change.
Output appears here3Level 3 · AdvancedGenerators, scope and when not to use them
Generator expressions save memory
Round brackets make a generator: sum(x * x for x in range(10**6)) computes items one at a time instead of building a million-item list. Use one whenever the result goes straight into sum, max, any, all or a loop.
Comprehensions have their own scope
The loop variable inside a comprehension doesn't leak out. But the walrus := lets you keep a computed value: [y for x in data if (y := x * x) > 50] works out x * x only once per item and keeps it.
Readability first
If a comprehension needs more than two fors, several conditions, or side effects like printing, write a normal loop. Comprehensions are for building values.
Example 6: List vs generator memory
The list stores all 100,000 numbers at once. The generator makes them one at a time, so it uses almost no memory, but it can only be used once.
Output appears hereExample 7: Scope and the walrus
Each average is worked out once and kept with :=, then reused as the value. The x inside the comprehension doesn't touch the x outside.
Output appears hereif matters. [x for x in a if x > 0] drops items, while [x if x > 0 else 0 for x in a] keeps every item and changes some. Writing [x for x in a if x > 0 else 0] is a SyntaxError.What does this print?
print([n * 2 for n in range(5) if n % 2 == 1])
50 graded problems are waiting in Topic Practice.