How it works
A comprehension builds a collection from an iterable in one expression, and is clearer than an accumulating loop when the logic is simple.
Use a comprehension for map-and-filter work; keep a loop when the body needs several statements.
Common error
Compressing complex logic into one comprehension, which trades readability for brevity.
Worked example
Python
values = [-2, 0, 3, 4]
squares = [value * value for value in values if value > 0]
print(squares)Output
[9, 16]The filter selects positive values before their squares are added to the result. Comprehensions are useful for simple transformations; clearer loops are preferable when the logic becomes complex.
Exercises
3.4.1 · Trace
Determine the exact output and explain the state changes.
Python
names = ["Ada", "Lin"]
print([f"{i}:{name}" for i, name in enumerate(names, start=1)])Show solution
Output
['1:Ada', '2:Lin']enumerate supplies both a position counter and the current value.
3.4.2 · Write code
Use a comprehension to keep even values from [1, 2, 3, 4, 5] and double them.
Show solution
Filter by evenness, then transform each kept value.
One valid solution
values = [1, 2, 3, 4, 5]
print([2 * x for x in values if x % 2 == 0])Expected output
[4, 8]