Sub topic 1
From a for loop to a comprehension
A comprehension is an expression that builds a new collection from an existing iterable. Many Python loops exist only to build a collection, and a comprehension states that purpose directly. This chapter shows how to turn such a loop into a comprehension, and how to tell when a loop does not fit the pattern. Later chapters cover filtering, nested clauses, dict and set forms, and generator expressions in detail.
Prerequisites
This chapter assumes you are comfortable with the following:
- Writing
forloops over arangeor over a list. - Using lists, dictionaries, and sets as built-in types.
- Writing boolean expressions with comparison operators such as
==,<, and%. - Calling functions and methods, including
list.append.
If you can read the loop in the next section without stopping, you are ready.
The loop pattern being replaced
A very common loop has three parts. It creates an empty list, walks over some iterable, and appends one computed value per item.
squares = []
for n in range(10):
squares.append(n * n)
print(squares) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] is NOT the result; see belowThe comment above is deliberately wrong. Run the code and compare the printed output with it. It prints [0, 1, 4, 9, 16, 25, 36, 49, 64, 81], because each item is squared before it is appended. Checking a claim against real output is a habit worth keeping while you refactor.
The loop does its job, but it spends three lines on bookkeeping: the empty list, the loop header, and the append call. The only information specific to this problem is the source, range(10), and the formula, n * n.
The same result as a comprehension
A list comprehension packs those two pieces into one expression.
squares = [n * n for n in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]Read it as "the list of n * n for each n in range(10)". The square brackets tell Python to build a list. Inside them, the formula comes first and the loop comes second.
Both versions produce the same list. You can confirm that with a comparison.
loop_result = []
for n in range(10):
loop_result.append(n * n)
comp_result = [n * n for n in range(10)]
print(loop_result == comp_result) # TrueMapping each loop part to its comprehension part
Every piece of the loop has a place in the comprehension. Learning this mapping lets you convert loops mechanically instead of by feel.
| Loop version | Comprehension version | Role |
|---|---|---|
| `squares = []` | The surrounding `[` and `]` | Creates the new list |
| `for n in range(10):` | `for n in range(10)` | Chooses the source and the loop variable |
| `squares.append(n * n)` | `n * n`, placed first | Computes the value for each item |
Note that the order changes. In the loop, the for header comes before the body. In the comprehension, the output expression is written first and the for clause follows. The loop still runs in the same order. Only the position on the page differs.
Transforming real data
The pattern is not limited to numbers. Any expression can be the output. Here the loop cleans a list of messy names.
names = [" ada ", "grace", " linus"]
cleaned = []
for name in names:
cleaned.append(name.strip().title())
print(cleaned) # ['Ada', 'Grace', 'Linus']The comprehension keeps the same logic and drops the scaffolding.
names = [" ada ", "grace", " linus"]
cleaned = [name.strip().title() for name in names]
print(cleaned) # ['Ada', 'Grace', 'Linus']The source can be any iterable: a list, a string, a file object, a dictionary's .items(), or another comprehension's result. The output expression can be any expression, including a function call, an arithmetic formula, a tuple, or a slice.
words = ["python", "loop", "list"]
pairs = [(w, len(w)) for w in words]
print(pairs) # [('python', 6), ('loop', 4), ('list', 4)]A working model: expression, not statement
The key idea behind the conversion is that a comprehension is an expression. It evaluates to a value, so you can assign it, pass it to a function, return it, or put it inside another expression.
print(len([n * n for n in range(10)])) # 10
print(max([len(w) for w in ["a", "bbb", "cc"]])) # 3A loop is a statement. It does not produce a value, so it needs a variable to collect results into. That variable has to be created first, mutated on each pass, and trusted to be correct at the end. A comprehension removes that mutable intermediate variable from your code. This is the real benefit. Shorter code is only a side effect. There is no half-built list sitting in a variable where other code could see it or change it.
A comprehension also always creates a new object. It never modifies an existing list in place. If your loop updates a list that already exists, you have a different problem, and a comprehension is not a direct replacement.
Common errors when converting
Most mistakes at this stage come from forcing a loop into a shape it does not have. These are the ones you will meet first.
Using a comprehension for its side effects
A comprehension is for building a value. If the loop body exists to do something, such as printing, writing to a file, or appending to another list, a comprehension is the wrong tool. It still runs, but it builds a pointless list of return values.
result = []
nones = [result.append(n * n) for n in range(3)]
print(result) # [0, 1, 4]
print(nones) # [None, None, None]The append call works, but nones is a list of None values that nobody wanted. It wastes memory and misleads readers, who will wonder why the list exists. If you only want the side effect, keep the plain loop.
Putting the clauses in the wrong order
The output expression must come before for. Writing the loop header first is a SyntaxError.
# SyntaxError: the output expression must come first
# squares = [for n in range(10) n * n]
squares = [n * n for n in range(10)]The same goes for stray punctuation. A trailing colon, as in [n * n for n in range(10):], is also a SyntaxError. A comprehension has no colon and no indented body.
Loops that carry state between iterations
A comprehension evaluates each item independently. If an iteration depends on a variable updated by earlier iterations, the loop does not map directly.
running = []
total = 0
for n in range(5):
total += n
running.append(total)
print(running) # [0, 1, 3, 6, 10]Here total changes on every pass and each output depends on all earlier items. Writing a comprehension would require hidden tricks that hurt readability. The standard library already has a tool for this exact job.
from itertools import accumulate
print(list(accumulate(range(5)))) # [0, 1, 3, 6, 10]Loops with several statements or early exits
A comprehension has room for one output expression. If the body needs several statements, a break, a continue with complex logic, or a try/except, keep the loop. A common middle path is to move the logic into a helper function and call it from the comprehension.
def parse_or_zero(text):
try:
return int(text)
except ValueError:
return 0
raw = ["10", "x", "30"]
numbers = [parse_or_zero(item) for item in raw]
print(numbers) # [10, 0, 30]The function holds the multi-statement logic, and the comprehension stays a single readable line.
A conversion checklist
When you see a loop and wonder whether it can become a comprehension, ask these questions in order.
- Does the loop start with an empty collection and add to it on every pass (or every pass that meets a condition)?
- Does each added value depend only on the current item, and not on values computed in earlier passes?
- Can the value be written as a single expression?
- Is the collection the only result of the loop, with no other side effects in the body?
If all four answers are yes, the loop can become a comprehension. If any answer is no, leave it as a loop, or restructure it first, for example by moving logic into a function.
What carries over to the other forms
The loop-to-comprehension idea is not limited to lists. The same three-part mapping applies to dictionaries and sets, with different brackets and a different output.
words = ["apple", "banana", "cherry"]
# Dict: output is key: value
lengths = {w: len(w) for w in words}
print(lengths) # {'apple': 5, 'banana': 6, 'cherry': 6}
# Set: output is a single value, and duplicates collapse
unique_lengths = {len(w) for w in words}
print(unique_lengths) # {5, 6}Square brackets build a list, curly braces with key: value build a dict, and curly braces with a single value build a set. Later chapters cover the details, including how duplicate keys behave and why an empty set must be written set().
Where a comprehension helps and where it does not
A comprehension is a good fit when the loop is a plain mapping from input items to output items. It is a poor fit when the loop is really a procedure. The deciding question is whether a reader can understand the code in one pass. Short comprehensions usually read faster than the loop they replace. A comprehension that needs scrolling, nested conditions, or a comment to explain it usually reads worse. The final chapter of this tutorial returns to that trade-off with concrete rules. For now, remember that conversion is a choice, and a plain loop is never wrong.
Exercises
Exercise
Rewrite this loop as a single list comprehension. doubled = [] for value in [3, 1, 4, 1, 5]: doubled.append(value * 2)
Show answer
doubled = [value 2 for value in [3, 1, 4, 1, 5]]. The result is [6, 2, 8, 2, 10]. The output expression value 2 comes first, followed by the for clause.
Exercise
A learner wrote shout = [print(w.upper()) for w in ["a", "b"]] to print each word in uppercase. What does the variable shout contain, and what should the code look like instead?
Show answer
shout contains [None, None], because print returns None. The comprehension was used only for its side effect. The clearer version is a plain loop: for w in ["a", "b"]: print(w.upper()).
Exercise
Which of these loops can be turned directly into a list comprehension, and why can't the other one? Loop A: lengths = [] for word in ["to", "be", "or"]: lengths.append(len(word)) Loop B: totals = [] running = 0 for n in [2, 4, 6]: running += n totals.append(running)
Show answer
Loop A can, as [len(word) for word in ["to", "be", "or"]], because each output depends only on the current item. Loop B cannot be converted directly, because each output depends on the running variable updated by earlier iterations. Use itertools.accumulate or keep the loop.