Lesson · Comprehensions & Expressive Iteration
List Comprehensions
55 min readList Comprehensions
List comprehensions express mapping and filtering over an iterable in one construct. They are concise when the transformation is simple and counterproductive when nested logic hides the intent.
Learning goals
- Label the three parts of a list comprehension (output expression,
forclause, optionalifclause) and say what each one does. - Convert an append-in-a-loop into a comprehension with identical output, and argue which version a reviewer reads faster.
- Predict the full contents of a nested comprehension over a matrix before running it.
- Use a conditional expression in the output position and explain how it differs from an
iffilter. - Recognize the point where extra clauses or side effects mean a plain loop is the better tool.
Mental model
A comprehension is a pipeline in one expression: the for clause pulls items from the source, the optional if clause decides which items survive, and the output expression maps each survivor into the new list. Writing the three parts on one line makes the evaluation order visible: filter first, then map, always against the current item. A second for clause adds an inner loop read left to right, and each outer item produces its own inner list.
Source, filter, output expression
filter first, then map, always on the current item
Mental model
the same mechanism as a compact list
[output_expression for item in iterable if condition]
mapping source filtering (optional)Core idea
A list comprehension replaces the append-in-a-loop pattern with a single expression that eagerly builds a new list: the for clause supplies items, the optional if clause keeps the matching ones, and the output expression transforms each kept item. Because the filter runs before the mapping, a condition sees raw input items, not transformed output. The construct stays readable while those three parts can be scanned in one pass; a second for clause or a side effect in the output expression is the signal to switch to a loop.
Mapping
Mapping in a comprehension transforms each input item into an output expression. Keep the transformation simple enough that the comprehension still reads left to right.
Filtering
Filtering keeps only inputs whose condition is true. In comprehensions, put the if clause after the iteration clause; in generator pipelines, preserve laziness when possible.
Nested comprehensions
Nested comprehensions represent nested iteration. They are concise for simple Cartesian or matrix-like transformations but become difficult to read when conditions or transformations are complex.
Conditional expressions
A conditional expression chooses one of two values with x if condition else y. Use it for compact value selection, not for long branches with side effects.
Readability boundaries
A comprehension is readable when its iteration, optional filter, and transformation fit in one mental pass. Use an ordinary loop when nesting or side effects make the expression difficult to scan.
Walkthrough
numbers = range(10)is the source iterable; arangeobject is lazy, and the comprehension consumes it once to produce ten items.- In
squares_of_even = [n * n for n in numbers if n % 2 == 0], the filter runs first for eachn, so only even items reach the mapping; the result is[0, 4, 16, 36, 64]. - The nested
matrix = [[row * 10 + col for col in range(3)] for row in range(2)]runs the outer loop twice, and each pass runs the inner comprehension overrange(3), giving[[0, 1, 2], [10, 11, 12]]. - Predict before running: the exact contents of
squares_of_evenin order, and both rows ofmatrix.
Experiments to try
- Change the source to
range(10, 0, -1)and predict the output before running; the source controls order, the mapping never reorders. - Replace the filter with a conditional expression,
[n * n if n % 2 == 0 else n for n in numbers], and compare its length withsquares_of_even; filtering drops items, a conditional expression never does. - Extract
n % 2 == 0into adef is_even(n):helper and use it as the filter; confirm the result is unchanged. - Add a third
forclause inside the nested comprehension and find the depth at which the expression stops reading in one pass.
Common mistakes
- Assuming the filter runs after the mapping: in
[n * n for n in numbers if n % 2 == 0]the condition tests the rawn, so a condition likeif n * n > 10computes the square only to decide, then throws that value away. - Using a comprehension for side effects, such as printing or appending inside the output expression: the list it builds is discarded, so the real work is invisible in the value the expression returns. A
forloop states that intent directly. - Forgetting the result is built eagerly:
[n * 2 for n in range(10_000_000)]allocates all ten million items before the next line runs, even if only a few are ever read. - Mixing up which loop an
ifclause belongs to in a nested comprehension: in[x for row in matrix for x in row if x > 0]the filter belongs to the inner loop, so moving it silently changes which items are tested.
Practice: Easy
- Write
doubles = [n * 2 for n in range(5)]in the REPL and confirm it produces[0, 2, 4, 6, 8]; rewrite it as aforloop withappendand check the outputs match. - Extend the worked example's filter to
if n % 2 == 0 and n != 0; write the predicted result before running it, then explain which clause changed. - Build
words = ["fig", "banana", "kiwi"]and use a comprehension to keep only words longer than three characters; name the part of the expression making the decision.
Practice: Medium
- Swap the two
forclauses in the nested comprehension (for coloutside,for rowinside) and describe how the result's shape differs from[[0, 1, 2], [10, 11, 12]]. - Use a conditional expression in the output position to label each
ninrange(10)as"even"or"odd", and explain why every input appears in the result. - Flatten a small matrix with
[value for row in matrix for value in row], then add a filter on the inner clause; move the filter to the outer clause and record how the two results differ.
Practice: Hard
- Grow the nested comprehension into a 10 by 10 multiplication table; predict the row count, the column count, and the value at
table[7][8]before running it, then verify withlenand indexing. - Build a boundary lab around
squares_of_even: an empty source, a source with one item, a filter that rejects everything, and a conditional expression that never takes theelsebranch; record each result and the mechanism that produces it. - Take an append-in-a-loop from your own code and convert it to a comprehension keeping behavior identical; list what disappeared (the accumulator, the
appendcall, or both) and note anything that became less obvious.
Lesson checklist
- I can point at the output expression, the
forclause, and theifclause in any list comprehension. - I can convert an append-in-a-loop and a comprehension into each other keeping the output identical.
- I can predict the shape and contents of a nested comprehension before I run it.
- I can say when clause count or side effects mean a plain loop is the right call.
Remember
A list comprehension is one eagerly evaluated expression that pulls items with `for`, keeps the matching ones with an optional `if`, and maps each survivor with the output expression. Keep the three parts scannable in one pass: add a second `for` clause only while the reading order stays obvious, and move to a loop as soon as it does not.
Interview angles
What is the main purpose of **Mapping**?+
Mapping in a comprehension transforms each input item into an output expression. Keep the transformation simple enough that the comprehension still reads left to right.
What should you pay attention to when using **Filtering**?+
Filtering keeps only inputs whose condition is true. In comprehensions, put the if clause after the iteration clause; in generator pipelines, preserve laziness when possible.
How does **Nested comprehensions** fit into this lesson?+
Nested comprehensions represent nested iteration. They are concise for simple Cartesian or matrix-like transformations but become difficult to read when conditions or transformations are complex.
Why is a list comprehension a poor home for side effects such as printing or appending inside the output expression?+
The comprehension already builds its own result list, so an output expression that exists only for its side effect produces a list that gets discarded, and the real work never shows up in any value the caller sees. A plain for loop makes that intent visible.