Sub topic 12
Readability: when a plain loop is better
This chapter assumes you can already write list, dict, and set comprehensions, use if filters and conditional expressions, and read nested for clauses. It covers how to decide when a comprehension helps and when a plain loop is the better choice.
The goal is clarity, not shortness
A comprehension is best when it describes one new collection built from one source, in a single readable line or a few short lines. A reader should be able to say what it produces without tracing it step by step.
Compare two versions of the same task: keep the even numbers and square them.
numbers = range(10)
# Loop
result = []
for n in numbers:
if n % 2 == 0:
result.append(n * n)
# Comprehension
result = [n * n for n in numbers if n % 2 == 0]
print(result) # [0, 4, 16, 36, 64]The comprehension wins here. It has one filter, one output expression, and no extra state.
Signs a comprehension has become too dense
Switch to a loop when you see any of these:
- Two or more
forclauses combined with filters, so you must work out the nesting order. - A conditional expression and a filter in the same comprehension.
- An output expression that calls several functions or spans multiple lines.
- A line that you have to read three times.
Here is a comprehension that crosses the line.
orders = [
{"id": 1, "items": [("pen", 2), ("book", 0)]},
{"id": 2, "items": [("lamp", 1)]},
]
# Hard to read
labels = [f"{o['id']}:{name.upper()}" if qty > 1 else f"{o['id']}:{name}"
for o in orders for name, qty in o["items"] if qty > 0]
print(labels) # ['1:PEN', '2:lamp']
# Clearer
labels = []
for order in orders:
for name, qty in order["items"]:
if qty == 0:
continue
label = f"{order['id']}:{name}"
if qty > 1:
label = label.upper()
labels.append(label)
print(labels) # ['1:PEN', '2:LAMP']The two versions do not produce the same result. The comprehension upper-cases only the name, while the loop upper-cases the whole label. The dense version made that mistake easy to write and hard to see. Spotting a slip like this is a good reason to prefer the loop.
Things a comprehension should not do
A comprehension is an expression that builds a value. Do not use it only for its side effects.
names = ["Ada", "Grace"]
# Avoid: builds a throwaway list of None values
[print(name) for name in names]
# Prefer
for name in names:
print(name)Use a loop in these cases too:
- You need
break, since a comprehension cannot stop early. - You need to handle exceptions per item with
tryandexcept. - You are updating several variables, such as a running total and a list, in one pass.
- You are building more than one collection from the same pass over the data.
Memory also matters
If you only need to consume the results once, as with sum, any, all, or max, a generator expression avoids building a list. Use a list comprehension when you need to index, reuse, or print the result.
A quick decision guide
| Situation | Better choice |
|---|---|
| Transform or filter one iterable into a list | List comprehension |
| Build a lookup table from pairs | Dict comprehension |
| Collect unique values | Set comprehension |
| Result is consumed once, such as by `sum` | Generator expression |
| Several branches, `break`, or `try` | Plain loop |
| Side effects such as printing or writing | Plain loop |
A middle path: extract a function
Sometimes the loop body is complex but the overall shape is still "one output per input". Move the logic into a function and keep a simple comprehension.
def label_for(order_id, name, qty):
label = f"{order_id}:{name}"
return label.upper() if qty > 1 else label
labels = [
label_for(o["id"], name, qty)
for o in orders
for name, qty in o["items"]
if qty > 0
]
print(labels) # ['1:PEN', '2:lamp']The function holds the detail and the comprehension shows the structure. Choose by asking what a teammate will understand fastest, and not by which version is shorter.
Exercise
Why is [print(n) for n in range(3)] a poor use of a list comprehension, and what should you write instead?
Show answer
It builds a list of None values that nobody uses, just to run print for its side effect. A plain loop states the intent directly: for n in range(3): print(n).
Exercise
You need to scan a list of numbers, stop at the first negative value, and collect everything before it. Can a comprehension do this, and which construct fits better?
Show answer
A comprehension cannot use break, so it cannot stop early. Use a for loop that appends each value and breaks when it finds a negative number.