Sub topic 2
List comprehension syntax
This chapter assumes you can write a for loop over range(), you know what a list is, and you can call functions and methods such as str.upper(). It covers the parts of a list comprehension, how Python evaluates them, and the syntax errors you are most likely to hit.
The three parts
A list comprehension is an expression that builds a new list. It has this shape:
[expression for item in iterable]iterableis any object you can loop over: a list, a string, arange, a dict, a file.itemis the name that holds each value in turn.expressionis evaluated once per item, and its result goes into the new list.
words = ["apple", "banana", "cherry"]
upper = [w.upper() for w in words]
print(upper) # ['APPLE', 'BANANA', 'CHERRY']
print(words) # ['apple', 'banana', 'cherry']The original list is unchanged. A comprehension always produces a new list, and the result has one entry per item in the iterable.
How Python evaluates it
Read the comprehension starting at the for. Python takes the next item from the iterable, binds it to the loop variable, evaluates the expression, and appends the result. The expression is written first, but it runs last in each round.
This is why the comprehension is equivalent to a loop that starts with an empty list and calls append on each pass.
The expression can be anything
The output expression may be an arithmetic expression, a method call, a function call, or the loop variable itself. It does not have to use the loop variable at all.
zeros = [0 for _ in range(3)]
print(zeros) # [0, 0, 0]
lengths = [len(w) for w in ["apple", "banana", "cherry"]]
print(lengths) # [5, 6, 6]By convention, _ names a loop variable you do not use.
Any iterable works
The source does not have to be a list. Iterating a string gives characters. Iterating a dict gives its keys.
letters = [ch for ch in "abc"]
print(letters) # ['a', 'b', 'c']
prices = {"tea": 3, "coffee": 4}
names = [name for name in prices]
print(names) # ['tea', 'coffee']
costs = [price for price in prices.values()]
print(costs) # [3, 4]For a dict, use .values() or .items() when you need more than the keys.
Producing tuples
To put a pair into each slot, wrap the expression in parentheses.
pairs = [(n, n * n) for n in range(4)]
print(pairs) # [(0, 0), (1, 1), (2, 4), (3, 9)]Without the parentheses, Python cannot tell where the expression ends, and it raises a SyntaxError.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Using `(...)` instead of `[...]` | You get a generator expression, not a list | Use square brackets |
| Leaving out the output expression, as in `[for n in range(3)]` | `SyntaxError` | Write the expression first |
| Writing the expression after the `for` clause | `SyntaxError` | Put the expression before `for` |
| Calling a function only for its side effect | The function runs, and you build a useless list | Use a plain `for` loop |
The last row deserves an example. This code prints correctly, but it also builds a list of None values that nobody wants.
results = [print(n) for n in range(3)]
print(results) # [None, None, None]A comprehension is for building a value. If you only want the effect of running code on each item, use a loop.
Reading a comprehension
When you meet an unfamiliar comprehension, read it in two steps. First find the for and ask what is being looped over. Then look back at the start and ask what is built from each item. Used this way, [len(w) for w in words] reads as "for each w in words, take len(w)".
cleaned = [
line.strip().lower()
for line in [" Hello ", "WORLD "]
]
print(cleaned) # ['hello', 'world']The next chapters add an if clause to this shape, which lets you drop items or choose between two values.
Exercise
What does [len(s) for s in "hi there".split()] return, and why is it not [8]?
Show answer
It returns [2, 5]. The call "hi there".split() produces the list ['hi', 'there'], so the loop runs twice. The expression len(s) is evaluated once per word, giving 2 and 5. The result has one entry per item in the iterable, not one entry for the whole string.
Exercise
Rewrite this loop as a list comprehension, and say what the output expression is. result = [] for n in range(4): result.append((n, n + 1))
Show answer
result = [(n, n + 1) for n in range(4)]. The output expression is (n, n + 1), and the parentheses are required to make a tuple. The result is [(0, 1), (1, 2), (2, 3), (3, 4)].