Comprehensions
A lot of Python code builds one collection from another: keep the valid rows, square every number, map ids to names. Comprehensions do that in one readable line instead of four. This lesson shows the shape, how to filter and choose values, how to read nested ones, and when a plain loop is clearer.
Foundations · Python for data engineers · Bronze · Built-in data structures, lesson 2 of 3
On this page
Read first: Lists, dicts and sets: what each operation costs (skip if you know it)
In plain words first
Picture telling a helper: "Go through the basket, and for every apple that is ripe, put a sliceslice: A piece of a list or string, xs[start:stop:step]. It always builds a new list; xs[::-1] is a reversed copy. Learn more → on the plate." That one sentence has three parts: what to go through (the basket), which items to take (ripe apples) and what to put down (a slice).
A comprehension is that sentence written in Python, in the order [slice for apple in basket if ripe]: what to put down first, then what to go through, then which ones to take.
The shape of a comprehension
A comprehension builds a new collection from an iterableiterable: Anything you can loop over with for: a list, a string, a dict, a range, a file. Calling iter() on it gives a fresh iterator. Learn more → in one expression: [expression for item in iterable if condition]. Read it as "for each item, if the condition holds, keep the expression". It replaces the common loop of "make an empty list, loop, append".
fares = [120, 45, 300, 80] high = [] for f in fares: if f >= 100: high.append(f * 1.05) high_too = [f * 1.05 for f in fares if f >= 100] print("loop: ", high) print("comprehension:", high_too)
Output from a real run
loop: [126.0, 315.0] comprehension: [126.0, 315.0]
Lists, dicts and sets
The brackets decide what you build: [...] a list, {k: v ...} a dict, {...} a set. A dict comprehension is the natural way to build an index or to transform every value of a dict.
riders = [("r1", "Pune"), ("r2", "Goa"), ("r3", "Pune")] names = [rid for rid, city in riders] city_of = {rid: city for rid, city in riders} cities = {city for _, city in riders} print(names) print(city_of) print(sorted(cities))
Output from a real run
['r1', 'r2', 'r3']
{'r1': 'Pune', 'r2': 'Goa', 'r3': 'Pune'}
['Goa', 'Pune']Filtering versus choosing
An if at the end filters: items that fail are dropped. An if/else before the for is a conditional expression that chooses a value for every item; nothing is dropped. Mixing them up is the most common comprehension bug.
minutes = [12, 45, 8, 60] late_only = [m for m in minutes if m > 30] labels = ["late" if m > 30 else "on time" for m in minutes] print(late_only) print(labels)
Output from a real run
[45, 60] ['on time', 'late', 'on time', 'late']
Nested comprehensions
Several for clauses run like nested loops, outermost first: [x for row in grid for x in row] reads "for row in grid: for x in row: keep x". It flattens exactly one level. Past two clauses, or with conditions on each level, a regular loop is easier to read and debug.
baskets = [["dosa", "chai"], [], ["biryani"]] items = [item for basket in baskets for item in basket] print(items)
Output from a real run
['dosa', 'chai', 'biryani']
(f * 2 for f in fares) is a generator expression: it produces items one at a time instead of building a list. Pass it straight to sum, max or any to save memory: sum(f for f in fares if f > 100).Common mistakes
- Putting if/else at the end of a comprehension —
[x for x in xs if c else y]is a syntax error. Choosing goes before the for; filtering after it. - Comprehensions for side effects —
[print(x) for x in xs]builds a useless list. Use a for loop when you only want the effect. - Three nested for clauses on one line — Correct but unreadable. Split into a loop or a helper function.
Key takeaways
- A comprehension is a compact "loop and append" with an optional filter.
- if at the end filters; if/else at the front chooses.
- Several for clauses read left to right, like nested loops.
- Use round brackets for a lazy generator expression.
Interview prep
THE QUESTION
"What is the difference between [f(x) for x in xs] and (f(x) for x in xs)?"
Avoid: "comprehensions are always faster, so I use them everywhere". They are somewhat faster than append loops, but readability decides, and side effects belong in loops.
Follow-ups · answer out loud, then open
Follow-up"How do you read [x for row in grid for x in row]?"
Scenario"You need the total of all fares over 100 from a 10 GB file. Comprehension or generator?"
Trap"[x if x > 0 for x in xs] filters out the non-positive values."
Check yourself
3 questionsWhat is [n * 2 for n in range(4) if n % 2]?
Show the answer
[2, 6]. Only odd n (1 and 3) pass the filter, then they are doubled.
Which builds a dict?
Show the answer
{k: v for k, v in pairs}. A dict comprehension uses key: value inside braces.
Which keeps every element, labelling each?
Show the answer
["pos" if x > 0 else "neg" for x in xs]. A conditional expression at the front chooses a value for every element.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · Built-in data structures · lesson 3 of 3 · 6 min readCounter, defaultdict and deque
Count, group and keep the last N with the collections module, and the traps in each.
Related lessons
Generators and lazy evaluationPython for data engineers · 7 min read
Lists, dicts and sets: what each operation costs
Previous: Lists, dicts and sets: what each operation costs
Primary sources: List comprehensions · Generator expressions