Sub topic 15
From for loops to list comprehensions
This chapter assumes you can write a for loop over a list or a range(), call append() on a list, and use if and else. It also assumes you know how enumerate() and zip() work. It shows how a common loop pattern, building a new collection from an iterable, can be written as a single expression. It also covers when you should keep the loop.
The pattern behind a comprehension
Many loops follow the same shape. They start with an empty list, walk over an iterable, and append one value per item.
squares = []
for n in range(1, 6):
squares.append(n * n)
print(squares) # [1, 4, 9, 16, 25]A list comprehension expresses the same thing in one expression:
squares = [n * n for n in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]The comprehension has the same parts as the loop. The for n in range(1, 6) clause is the loop header. The expression n * n is the value you would pass to append(). The only change is that the value comes first, so you read it as "n squared for each n in the range".
Adding a filter
An if placed after the for clause skips items for which the condition is false. It does the job of an if plus continue in a loop.
evens = [n for n in range(10) if n % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]The equivalent loop is:
evens = []
for n in range(10):
if n % 2 == 0:
evens.append(n)Filter versus conditional expression
An if at the end filters items out. An if ... else at the front chooses between two values for every item. These two uses look alike but sit in different places, and mixing them up is a common error.
labels = ["even" if n % 2 == 0 else "odd" for n in range(4)]
print(labels) # ['even', 'odd', 'even', 'odd']An else after the for clause is a syntax error, because a filter has no "otherwise" branch. If you need both a front expression and a filter, you can use both: [x * 2 if x > 0 else 0 for x in data if x is not None].
Several for clauses
A comprehension can contain more than one for clause. The clauses nest in the order you write them, so the first one is the outer loop.
pairs = [(i, j) for i in range(1, 4) for j in range(1, 4) if i < j]
print(pairs) # [(1, 2), (1, 3), (2, 3)]This matches the nested loop you saw earlier in the chapter on nested loops:
pairs = []
for i in range(1, 4):
for j in range(1, 4):
if i < j:
pairs.append((i, j))Flattening a list of lists is the usual practical case:
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [x for row in matrix for x in row]
print(flat) # [1, 2, 3, 4, 5, 6]Readers often find the order confusing here. The clause order reads like the nested loops written top to bottom, while the result expression is moved to the front. Two for clauses is a sensible limit. Beyond that, write the loops out.
Dict, set, and generator forms
The same syntax works with other brackets. The bracket type decides what you build.
| Syntax | Result | Example |
|---|---|---|
| `[expr for x in it]` | list | `[n * n for n in range(4)]` |
| `{expr for x in it}` | set | `{len(w) for w in words}` |
| `{k: v for x in it}` | dict | `{name: score for name, score in zip(names, scores)}` |
| `(expr for x in it)` | generator | `(n * n for n in range(4))` |
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 72]
by_name = {name: score for name, score in zip(names, scores)}
print(by_name) # {'Ada': 95, 'Grace': 88, 'Linus': 72}
words = ["apple", "fig", "kiwi", "plum"]
print(sorted({len(w) for w in words})) # [3, 4, 5]The set comprehension drops duplicates, since kiwi and plum both have length 4. A dict comprehension keeps the last value if a key repeats.
There is no tuple comprehension. Round brackets create a generator expression instead.
Generator expressions
A generator expression looks like a list comprehension, but it does not build a list. It produces one value at a time when something asks for it. This is the same lazy idea you met with range. It is the right choice when you only want to consume the values once, for example to feed sum(), max(), any(), or all().
total = sum(n * n for n in range(10))
print(total) # 285
has_negative = any(x < 0 for x in [3, 5, -1, 8])
print(has_negative) # TrueWhen a generator expression is the only argument to a function, you can drop the extra pair of parentheses, as shown above. any() also stops at the first true value, so it does not have to look at the rest of the data. A list comprehension in the same place would build the entire list first.
A generator is single-use. Once you have iterated over it, it is exhausted, and a second loop over the same object sees nothing.
gen = (n for n in range(3))
print(list(gen)) # [0, 1, 2]
print(list(gen)) # []Scope: the loop variable stays inside
In a plain for loop, the loop variable remains bound after the loop ends. A comprehension has its own scope, so its variable does not leak out.
i = "outer"
squares = [i * i for i in range(3)]
print(i) # outer
print(squares) # [0, 1, 4]The i inside the comprehension is a separate variable from the i outside. This removes one source of accidental overwrites, which the plain loop does not protect against.
What a comprehension cannot do
A comprehension is an expression that produces a collection. Some loop features have no equivalent.
break: there is no way to stop early. Use a loop, oritertools.takewhile()if the stopping rule is a condition on the items.- Loop
else: there is no equivalent. - Statements in the body: you cannot use assignments,
try, orprint()as a step. Only expressions are allowed. - Side effects as the goal: writing
[print(n) for n in range(3)]also works, but it builds a throwaway list ofNonevalues. If you do not need the result, use a plainforloop.
When to keep the loop
Prefer a comprehension when the result is a collection and the logic is a single transformation, optionally with a filter. Prefer a loop when any of these apply:
- The body needs several statements or temporary variables.
- You need
break,continuebeyond a simple filter, or the loopelse. - The comprehension would need more than two
forclauses, or a long condition that does not fit on one or two lines. - You are updating several results at once, such as a running total and a list.
If you do write a long comprehension, split it across lines. Python allows line breaks inside the brackets:
result = [
word.upper()
for word in words
if len(word) > 3
]
print(result) # ['APPLE', 'KIWI', 'PLUM']Putting each clause on its own line keeps the structure visible and lets you compare it to the loop it replaces.
Common errors
- Putting
elseat the end:[x for x in data if x > 0 else 0]is a syntax error. Move theif ... elseto the front:[x if x > 0 else 0 for x in data]. - Expecting a tuple:
(x for x in data)is a generator, not a tuple. Usetuple(x for x in data)if you need one. - Reusing a generator: a second pass over an exhausted generator yields nothing, with no error.
- Modifying the source list inside the comprehension: this has the same problems described in the chapter on mutating a list while looping. Build the new list from the old one and then rebind the name.
Exercise
Rewrite this loop as a single list comprehension, then say what it returns for words = ["sky", "tree", "moon", "a"].
result = []
for w in words:
if len(w) > 2:
result.append(w.upper())
Show answer
result = [w.upper() for w in words if len(w) > 2]. It returns ['SKY', 'TREE', 'MOON'], because only "a" fails the length test.
Exercise
What does [x * 2 if x % 2 == 0 else x for x in range(5)] return, and why is there no filter in it?
Show answer
It returns [0, 1, 4, 3, 8]. The if ... else before the for is a conditional expression that chooses a value for every item, so no item is dropped. Even numbers are doubled and odd numbers are kept as they are.
Exercise
You need to check whether any line in a file with millions of lines contains the word "ERROR". Should you use any([ "ERROR" in line for line in f ]) or any("ERROR" in line for line in f)?
Show answer
Use the generator form, any("ERROR" in line for line in f). It tests one line at a time and any() stops at the first match. The list form reads and tests every line and stores all the results before any() starts.