A comprehension builds a collection by expressing how to visit inputs, filter them and produce output values.
Read execution order, construct lists and mappings and see how a set removes duplicate result values.
A comprehension describes how to build a collection, but its first-written expression is not the first thing evaluated. Follow binding, filtering, and transformation in execution order. Then choose list, set, or dict according to whether order, duplicates, and repeated keys need to survive in the result.
![Two lanes doing the same job: the top lane is a factory line — raw items enter, a gate keeps only the ones passing a test, a stamping tool transforms what's left, finished items exit — labelled "[transform for item in items if test]"; the bottom lane is the same four steps drawn as a plain for-loop with an if and an append, taking up four times the space](/api/assets/python/assets/1746396fd9154cde.png)
Build a festival price list
A café wants a quick list of festival prices — only for items under ₹100, each one 20% off. The loop version and the comprehension build the exact same list:
Read the comprehension as three parts, always in this order: what to keep
(round(p * 0.8, 2)), where from (for p in prices), which ones
(if p < 100). Leave off the if and every item survives, just transformed.
Preparing this topic’s interactive investigation…
Read syntax order separately from execution order
The output expression appears first on the page, but it runs only after a candidate has been bound and its filters have passed. This lets a filter protect a transformation that would otherwise fail.
The empty and whitespace-only strings are rejected before int(text) runs.
Changing the condition to if int(text) would try conversion too soon and
would also discard a valid "0". To accept arbitrary text, a named parsing
function or a loop with exception handling is clearer than a clever expression.
For a nested comprehension, expand for clauses left to right as nested
loops. [x for row in matrix for x in row] first chooses a row, then one
element of that row. A filter after the first for can skip a whole row;
a filter after the second can skip individual elements.
A new outer collection does not imply copied elements. [row for row in rows]
still shares every row object, linking back to the data-model lesson. Sets
discard duplicates and have no promised presentation order; dicts overwrite
repeated keys with the last value. Choose the output type from what information
must survive, not just the shortest syntax.
Transfer the menu task to duplicate item names and a zero-price item. Predict whether one price disappears and whether zero survives. If both duplicate items must be retained, a mapping from name to one price is the wrong result shape.
De-duplicate customer emails
A signup form collects emails with mixed case and stray spaces. A set comprehension both normalises and drops duplicates in one line, because a set can never hold the same value twice:
Three inputs, two customers — "Asha@mail.com" and "asha@MAIL.com " normalise to the same string, so the set keeps only one. A list comprehension here would keep all three, because a list allows repeats.
words = ["apple", "apricot", "banana", "blueberry"]
by_letter = {w[0]: w for w in words}
print(by_letter)Menu name → price lookup
Two parallel lists — names and prices, same order — become one dict with
zip, which pairs them up position by position:
zip(names, prices) hands out ("Tea", 20), then ("Coffee", 30), then
("Sandwich", 60) — the comprehension's for name, price in ... unpacks
each pair as it arrives, same as it would in a plain for loop.
Where a comprehension stops paying off
A matrix of daily orders per stall needs flattening into one list. One for
per level of nesting, read left to right, outermost first:
matrix = [[1, 2], [3, 4], [5]]
flat = [x for row in matrix for x in row]
print(flat)That's the limit worth knowing: one for plus a nested for is still
readable. Add a second if, or nest a comprehension inside another one's
expression, and a written-out loop with named steps gets easier to debug and
to read — don't force everything into one line.
A comprehension's loop variable is also its own: it never escapes, unlike a
plain for loop's variable (lesson 1).
Quick practice
scores = [55, 90, 38, 72]
passed = [s for s in scores if s >= 40]
print(passed, len(scores))Fix the condition so only orders under ₹100 remain.
fruits = ["fig", "kiwi", "apple", "pear"]
lengths = {len(f) for f in fruits}
print(sorted(lengths))matrix = [[1, 2, 3], [4, 5, 6]]
totals = [sum(row) for row in matrix]
print(totals)🎯 Your turn
Write veg_menu(items). Each item is a dict with "name", "price" and
"veg". Return a dict comprehension: {name: discounted price} for
only the vegetarian items, each price cut by 10% and rounded to 2
decimals.
veg_menu([{"name": "Paneer Wrap", "price": 120, "veg": True}])→{"Paneer Wrap": 108.0}- Non-veg items don't appear in the result at all.
Hint: {item["name"]: round(item["price"] * 0.9, 2) for item in items if item["veg"]} — one line, all three parts of a comprehension.
Press ▶ Run, try the Live App chips, then ✓ Check. After that, the practice set below goes from a filtered list to a full dict pipeline.
Practice — level up
0/5 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write squares_of_evens(nums) returning a LIST comprehension of the squares of only the even numbers in nums, in their original order.
Write unique_lengths(words). Build a SET comprehension of the distinct lengths of the strings in words (no duplicates), then return it as a sorted list so the result is easy to compare.
Write name_to_price(names, prices) returning a dict comprehension pairing each name with its price at the same position, using zip.
Write flatten_matrix(matrix), where matrix is a list of lists. Return one flat LIST of every number, in order, using a comprehension with TWO for clauses (no .extend, no nested loop written out).
Each order is a dict with "id", "amount" and "cancelled". Write categorize_orders(orders) returning a dict comprehension {id: label} for every NON-cancelled order, where label is "rush" for amounts over 500 and "normal" otherwise. One line: a filter if, a key, and a conditional expression for the value.