Sub topic 2
List comprehension syntax
This chapter assumes you can write a for loop over range and other iterables, use append on a list, and read a basic comparison such as n > 3. The previous chapter showed the loop-to-comprehension rewrite once. Here you learn the syntax precisely, so you can predict what any list comprehension does before you run it.
The shape of a list comprehension
A list comprehension is an expression that builds a new list. Its minimal form has three parts inside square brackets:
[ expression for target in iterable ]- The iterable is anything you can loop over: a list, a string, a
range, a dictionary, a file, a generator. - The target is the name (or names) that receives each item in turn.
- The expression is evaluated once per item, after the target is bound. Its value becomes one element of the new list.
A concrete example:
words = ["apple", "banana", "cherry"]
upper = [w.upper() for w in words]
print(upper) # ['APPLE', 'BANANA', 'CHERRY']Here words is the iterable, w is the target, and w.upper() is the expression. The equivalent loop is:
words = ["apple", "banana", "cherry"]
upper = []
for w in words:
upper.append(w.upper())
print(upper) # ['APPLE', 'BANANA', 'CHERRY']The expression comes first in the text but runs last in each pass. Reading the for part first often makes a comprehension easier to understand: "for each w in words, produce w.upper()."
How Python evaluates it
The steps below are what Python does for every list comprehension.
Three consequences follow from this model:
- The result is always a new list. The source iterable is read, not modified.
- The result has one element per item when there is only a
forclause. An empty iterable gives[]. - The expression runs once per item, in order. If the expression has side effects, they happen in iteration order.
nums = [1, 2, 3]
doubled = [n * 2 for n in nums]
print(doubled) # [2, 4, 6]
print(nums) # [1, 2, 3] (unchanged)
print([n * 2 for n in []]) # []If you want to replace the contents of an existing list, assign to a slice. This keeps the same list object, which matters if other names refer to it:
nums = [1, 2, 3]
alias = nums
nums[:] = [n * 2 for n in nums]
print(alias) # [2, 4, 6]Mapping the loop to the comprehension
| Loop version | Comprehension part |
|---|---|
| `result = []` | The surrounding `[` and `]` |
| `for target in iterable:` | `for target in iterable` |
| `result.append(expression)` | `expression` at the front |
Only loops whose body is a single append of one value fit this mapping directly. A loop that appends in several places, updates other variables, or uses break has no direct comprehension form.
What can go in the expression
The expression can be any single Python expression: arithmetic, a function call, a method call, an f-string, indexing, or a conditional expression.
text = "3 14 15 92"
numbers = [int(s) for s in text.split()]
print(numbers) # [3, 14, 15, 92]
names = ["ada", "grace"]
greetings = [f"Hello, {n.title()}!" for n in names]
print(greetings) # ['Hello, Ada!', 'Hello, Grace!']The expression does not have to use the target. This is the standard way to build a list of a given length:
zeros = [0 for _ in range(3)]
print(zeros) # [0, 0, 0]The name _ is a convention meaning "I do not use this value." It is a normal variable name, and Python does not treat it specially here.
An expression cannot be a statement. Assignments such as x = 1, return, pass, and del are not allowed. If you need one of those, use a loop.
Producing tuples requires parentheses
If you want each element to be a tuple, wrap it in parentheses. Without them the comma is ambiguous, and Python rejects the code.
names = ["ada", "grace"]
pairs = [(n, len(n)) for n in names]
print(pairs) # [('ada', 3), ('grace', 5)]
# [n, len(n) for n in names] # SyntaxError: the tuple needs parenthesesWhat can go in the iterable
Any iterable works. The iterable is evaluated once, before the first item is taken.
print([ch for ch in "abc"]) # ['a', 'b', 'c']
print([n for n in range(3, 8, 2)]) # [3, 5, 7]
ages = {"ada": 36, "grace": 45}
print([k for k in ages]) # ['ada', 'grace']
print([v for v in ages.values()]) # [36, 45]
print([f"{k}={v}" for k, v in ages.items()]) # ['ada=36', 'grace=45']Iterating over a dictionary directly gives its keys. Use .values() or .items() when you need the other parts.
Unpacking in the target
The target can be several names, exactly as in a for loop. Python unpacks each item into them. The item must have a matching number of parts, or you get a ValueError.
points = [(1, 2), (3, 4), (5, 6)]
xs = [x for x, y in points]
sums = [x + y for x, y in points]
print(xs) # [1, 3, 5]
print(sums) # [3, 7, 11]This is why enumerate and zip pair so well with comprehensions:
letters = "abc"
indexed = [f"{i}:{ch}" for i, ch in enumerate(letters)]
print(indexed) # ['0:a', '1:b', '2:c']
a = [1, 2, 3]
b = [10, 20, 30]
totals = [x + y for x, y in zip(a, b)]
print(totals) # [11, 22, 33]Nested unpacking works too, as long as the structure matches:
records = [("ada", (36, "UK")), ("grace", (45, "US"))]
countries = [country for name, (age, country) in records]
print(countries) # ['UK', 'US']Iterators are consumed
A comprehension reads its iterable to the end. If that iterable is an iterator (an object that can be read only once), it is empty afterward.
it = iter([1, 2, 3])
first = [n for n in it]
second = [n for n in it]
print(first) # [1, 2, 3]
print(second) # []Lists, strings, ranges, and dictionaries can be iterated repeatedly. Generators, file objects, and the results of map and zip cannot. If you get an unexpectedly empty result, check whether something already consumed the iterator.
Comprehension versus `list()` and `map`
You will meet several ways to build the same list.
nums = [1, 2, 3]
a = [n * n for n in nums]
b = list(map(lambda n: n * n, nums))
c = list(nums) # copy, no transformation
d = [n for n in nums] # also a copy, but list(nums) is clearer
print(a == b, c == d) # True TrueUse a comprehension when the work is "transform each item with an expression." Prefer list(iterable) when you only need to turn an iterable into a list without changing it. map with a lambda is rarely clearer than the comprehension. map(str, items) with an existing function is fine.
On speed: a comprehension is usually somewhat faster than the equivalent append loop, because it avoids looking up and calling append for each item. The gain is small. Choose by readability, and measure with timeit only if performance matters.
Common errors at this level
- Using a comprehension for side effects.
[print(n) for n in range(3)]works, but it builds a list ofNonevalues that you throw away. Use a plainforloop when you want an action and not a value. - Forgetting the brackets' meaning.
(n * n for n in range(3))with parentheses is a generator expression, not a tuple. Later chapters cover it.[...]always gives a list. - Expecting in-place change. A comprehension never modifies its source. Assign the result to a name, or use slice assignment as shown earlier.
- Mismatched unpacking.
[a for a, b in [(1, 2, 3)]]raisesValueError: too many values to unpack. The target pattern must match the item shape. - Over-long expressions. If the expression needs several lines or nested calls to read, give part of it a name with a helper function.
def clean(line):
return line.strip().lower()
lines = [" Alpha ", "BETA", " Gamma "]
print([clean(line) for line in lines]) # ['alpha', 'beta', 'gamma']Where this fits next
This chapter covered the core form: one expression, one for clause. The same skeleton is extended in later chapters. A trailing if filters items, an if/else in the expression chooses between values, extra for clauses nest loops, and swapping the brackets or adding key: value gives sets and dictionaries. Each extension keeps the evaluation model above, so a solid grasp of it carries forward.
Exercise
Rewrite this loop as a single list comprehension, then say what result contains.
data = [("a", 1), ("b", 2), ("c", 3)]
result = []
for letter, number in data:
result.append(letter * number)
Show answer
result = [letter number for letter, number in data]. It contains ['a', 'bb', 'ccc']. The tuple is unpacked into letter and number, and the expression letter number repeats the string number times.
Exercise
Why does [n, n * n for n in range(3)] fail, and what is the corrected line? What does the corrected line produce?
Show answer
It fails with a SyntaxError because a tuple element inside a comprehension must be parenthesized. The corrected line is [(n, n * n) for n in range(3)]. It produces [(0, 0), (1, 1), (2, 4)].
Exercise
The code below prints two lists. What are they, and why is the second one what it is? it = iter("abc") print([ch.upper() for ch in it]) print([ch.upper() for ch in it])
Show answer
The first line prints ['A', 'B', 'C']. The second prints []. The first comprehension consumes the iterator completely, so the second one finds nothing left to read.