Lab: think in comprehensions
Practice rewriting loops as comprehensions and shaping data the Pythonic way.
- Express transform-and-filter logic as a comprehension
- Use a nested comprehension to flatten data
- Recognise when a comprehension improves clarity
Optional lab. Hands-on practice with comprehensions — write, run, and check your work. The goal is to start reaching for a comprehension when the shape fits, while keeping it readable.
Warm up: same result, two ways
A comprehension is a loop that builds a collection, written as one expression. Run this to see the loop and the comprehension produce identical output:
Read the comprehension left to right: the value (n * 10), where from
(for n in nums), the filter (if n % 2 == 0).
Checkpoint 1 — squares of the evens
Write evens_squared using a single comprehension.
Write evens_squared(nums) returning a list of the squares of just the even numbers, in order.
evens_squared([1, 2, 3, 4]) → [4, 16]Checkpoint 2 — flatten
Comprehensions can have two for clauses to walk nested data. Flatten a list of
lists into a single list, preserving order.
Write flatten(rows) that turns a list of lists into one flat list. flatten([[1,2],[3]]) -> [1,2,3].
flatten([[1, 2], [3]]) → [1, 2, 3]The pattern is [item for row in rows for item in row] — read the for clauses
left to right, outer first. If a comprehension ever gets harder to read than the
loop, that's your signal to use the loop.
Done?
Two green checks and you're thinking in comprehensions. Next in the module: generators, for when you don't want to build the whole list at once.