Sub topic 12
Readability: when a plain loop is better
This chapter assumes you can already write list, dict, and set comprehensions with if filters and conditional expressions. It also assumes you have seen multiple for clauses and generator expressions. The goal is to decide when not to use them. A comprehension is a tool for building a collection from an iterable in one clear expression. When the expression stops being clear, a plain loop is the better choice.
What "readable" means for a comprehension
A comprehension is easy to read when a reader can say what it builds in one pass. Roughly: "a list of X, for each Y, where Z." The reader should not need to stop and decode it.
Comprehensions have a real advantage. They state that the result is a new collection built from the input, and they leave out the setup lines (result = [], result.append(...)). That advantage disappears when the body needs several steps, error handling, or side effects. At that point the comprehension is shorter but harder to follow, and shorter code that is harder to follow is not better.
Signs that a comprehension has grown too far
Look at this comprehension. It flattens rows, skips empty rows, skips one value, and replaces negatives with zero:
data = [[1, -2, 3], [], [4, 5, -6]]
result = [x * 2 if x > 0 else 0 for row in data if row for x in row if x != 3]
print(result) # [2, 0, 8, 10, 0]It works, but you have to check the clause order and work out which if belongs to which for. Here is the same logic as a loop:
data = [[1, -2, 3], [], [4, 5, -6]]
result = []
for row in data:
if not row:
continue
for x in row:
if x == 3:
continue
result.append(x * 2 if x > 0 else 0)
print(result) # [2, 0, 8, 10, 0]The loop is longer, but each rule has its own line. You can add a comment, a print, or a breakpoint to any line.
These are common signs that a loop would be clearer:
- The comprehension has more than two
fororifclauses combined. - It mixes a trailing filter, an
if/elsein the output expression, and nestedforclauses. - You cannot fit it in one screen line without reformatting it into many lines.
- You need to explain it with a comment before anyone can read it.
Things a comprehension cannot express
A comprehension holds only expressions. Some tasks need statements, and those belong in a loop.
Error handling
There is no try/except inside a comprehension. If some inputs may fail, a loop lets you handle each failure where it happens. This loop parses name,age lines, skips blank lines and comments, and records bad lines:
lines = ["alice,34", "", "# comment", "bob,x", "carol,29"]
people = {}
errors = []
for number, line in enumerate(lines, start=1):
line = line.strip()
if not line or line.startswith("#"):
continue
name, _, age_text = line.partition(",")
try:
people[name] = int(age_text)
except ValueError:
errors.append(f"line {number}: bad age {age_text!r}")
print(people) # {'alice': 34, 'carol': 29}
print(errors) # ["line 4: bad age 'x'"]This loop builds two results in one pass. A comprehension builds exactly one collection, so you would have to loop twice or hide the second result somewhere.
Early exit
A comprehension always consumes its whole input. There is no break. If you need to stop at the first match, use a loop, or use next() with a generator expression:
numbers = [3, 8, 12, 5, 20]
first_big = next((n for n in numbers if n > 10), None)
print(first_big) # 12Running totals and other state
If each item depends on the previous result, a loop with a variable is usually clearer than a trick built into a comprehension:
amounts = [10, -3, 5, -8, 4]
balances = []
balance = 0
for amount in amounts:
balance += amount
balances.append(balance)
print(balances) # [10, 7, 12, 4, 8](For this exact task, itertools.accumulate is also a good fit. A comprehension is not.)
Side effects do not belong in comprehensions
A comprehension is meant to build a value. Using it only to call a function for its effect creates a throwaway list:
names = ["ada", "grace"]
result = [print(n) for n in names]
print(result) # [None, None]This prints the names, but it also builds a list of None values that nobody wants. Readers will wonder whether the list is used. Write the loop instead:
names = ["ada", "grace"]
for n in names:
print(n)The same applies to [items.append(x) for x in data], [file.write(line) for line in lines], and similar patterns.
Avoiding repeated work
A filter and an output expression often need the same computed value. Calling the function twice is wasteful and can be wrong if the function is not pure:
def normalize(s):
return s.strip().lower()
words = [" Apple", "apple ", " Pear", ""]
cleaned = [normalize(w) for w in words if normalize(w)]
print(cleaned) # ['apple', 'apple', 'pear']An assignment expression computes the value once:
def normalize(s):
return s.strip().lower()
words = [" Apple", "apple ", " Pear", ""]
cleaned = [n for w in words if (n := normalize(w))]
print(cleaned) # ['apple', 'apple', 'pear']This is fine for a single reuse. If you need more than one temporary value, the walrus operator starts to crowd the line, and a loop with named variables is clearer.
Moving logic into a named function
Often the best fix is neither a loop nor a bigger comprehension. You can move the messy part into a function with a descriptive name and keep the comprehension short:
def parse_age(text):
try:
value = int(text)
except ValueError:
return None
return value if 0 <= value <= 130 else None
raw = ["34", "x", "200", "29"]
ages = [age for text in raw if (age := parse_age(text)) is not None]
print(ages) # [34, 29]The function holds the error handling and the range rule. It has a name, so you can test it alone. The comprehension then reads as "the valid ages from the raw text." Use this approach when the per-item logic is complex but the overall shape is still "one output per input, with a filter."
Formatting long comprehensions
If a comprehension is still the right choice but does not fit on a line, put each clause on its own line. Python allows line breaks inside brackets:
users = [
{"email": "[email protected]", "active": True},
{"email": "", "active": True},
{"email": "[email protected]", "active": False},
{"email": "[email protected]", "active": True},
]
active_emails = [
user["email"].lower()
for user in users
if user["active"]
if user["email"]
]
print(active_emails) # ['[email protected]', '[email protected]']The output expression, each for, and each if line up in a column, so the structure shows. Two if clauses in a row behave like and. Both must be true for an item to be kept.
If the multi-line version still needs careful study, switch to a loop.
Readability and memory: choose the form deliberately
Readability is not the only criterion. The form also decides whether the whole result is stored.
A generator expression is a good fit when you only consume the items once, for example inside sum, any, all, min, max, or "".join. It also stops early when the consumer stops:
numbers = range(1, 1_000_000_000)
print(any(n % 7 == 0 for n in numbers)) # TrueThe check ends at 7. Building a list of a billion items first would use a great deal of memory and time.
Use a list comprehension when you need the result more than once, need its length, or need to index into it. A generator is exhausted after one pass, so a second loop over the same generator sees nothing.
A decision guide
The same ideas as a table:
| Situation | Prefer |
|---|---|
| One output per input, simple filter | Comprehension |
| Result used once by `sum`, `any`, `all`, `join` | Generator expression |
| Per-item logic is complex but pure | Helper function plus comprehension |
| `try`/`except`, `break`, or running state | Plain loop |
| Calling a function only for its effect | Plain loop |
| Building two or more collections in one pass | Plain loop |
Debugging and maintenance
Plain loops are easier to debug. You can set a breakpoint on one line, print an intermediate value, or add a log call. Doing the same inside a comprehension means rewriting it. Tracebacks also point at the whole comprehension line, not the clause that failed.
Think about the next person who edits the code. A loop is easy to extend with one more condition. A dense comprehension often has to be rewritten first. If you expect the rule to grow, start with the loop.
Common mistakes in this area
- Squeezing logic into a comprehension because it is shorter, not because it is clearer.
- Using a comprehension for side effects and ignoring the resulting list.
- Calling an expensive function in both the filter and the output expression.
- Using a generator expression and then iterating over it twice.
- Writing a comprehension with three or more
forclauses. At that point, nested loops are almost always easier to read.
Practice
Exercise
A teammate writes [log.append(x) for x in values if x > 0] to record the positive values in log. What is wrong with it, and what would you write instead?
Show answer
The comprehension is used only for its side effect. It calls log.append for each positive value and builds a useless list of None values. Use a loop: for x in values: followed by an indented if x > 0: log.append(x). If you want a list of the positive values, build it directly with log = [x for x in values if x > 0].
Exercise
You need the first element of numbers that is divisible by 7, or None if there is none. The list is very large. Which form do you choose, and why not a list comprehension followed by [0]?
Show answer
Use next((n for n in numbers if n % 7 == 0), None). The generator expression stops at the first match, so it does not examine the rest of the list and does not build a result list. A list comprehension would check every element and store every match, and [0] would raise IndexError when there is no match.
Exercise
Rewrite this as something more readable and say why: [(a, b) for a in range(5) for b in range(5) if a != b if (a + b) % 2 == 0 if a < b].
Show answer
The three if clauses are combined filters, and one of them is redundant, because a < b already implies a != b. A clearer version keeps the comprehension but drops the redundant test and lays it out on several lines: [(a, b) for a in range(5) for b in range(5) if a < b and (a + b) % 2 == 0]. If more rules were expected, a nested for loop with continue statements would make each rule easier to read and change.