Sub topic 11
Reusing a computed value with the walrus operator
This chapter assumes you can write list, dict, and set comprehensions with if filters. It also assumes you know that a comprehension has its own scope (covered earlier in this tutorial). You need Python 3.8 or later to run the examples.
The problem: computing the same value twice
A comprehension often needs a computed value in two places. The if clause uses it to decide whether to keep an item, and the output expression uses it to build the result. Without extra syntax you have to compute it twice.
calls = 0
def slow_square(n):
global calls
calls += 1
return n * n
twice = [slow_square(n) for n in range(5) if slow_square(n) > 3]
print(twice, calls) # [4, 9, 16] 8The filter calls slow_square for all five items. The output expression calls it again for the three items that passed. That makes eight calls where five would do. If the function is slow, does I/O, or returns a different value each time (a random number or a timestamp), the duplication is a real cost or even a bug.
The assignment expression
Python 3.8 added the assignment expression, written name := expression. It is nicknamed the walrus operator because := looks like a walrus lying on its side. It does two things at once. It evaluates the expression and binds the result to the name, and the whole name := expression is itself a value, equal to the result.
You can put it in the filter and use the name in the output:
calls = 0
def slow_square(n):
global calls
calls += 1
return n * n
once = [sq for n in range(5) if (sq := slow_square(n)) > 3]
print(once, calls) # [4, 9, 16] 5Each item now costs one call. The if clause computes slow_square(n), stores it in sq, and compares it to 3. When the test passes, the output expression reads sq instead of calling the function again.
The same pattern appears in the chapter's basic example:
results = [y for n in range(5) if (y := n * n) > 3]
print(results) # [4, 9, 16]Evaluation order matters
Inside a comprehension, each item is processed in a fixed order. The for clause supplies the item. The if clause runs next. The output expression runs last, and only for items that passed the filter. The name must be bound before anything reads it, so the walrus belongs in the if clause, and the output expression uses the name afterward.
If you reverse the roles, Python reads the name before it exists:
try:
bad = [(square := n * n) for n in range(5) if square > 3]
except NameError as error:
print(error) # name 'square' is not definedThe filter square > 3 runs first, on the first item, before any := has run.
Why the parentheses are required
In the examples above, the walrus expression is wrapped in parentheses: (y := n * n) > 3. Without them, the condition would not mean what you want. Python's grammar does not allow an unparenthesized assignment expression in the if clause of a comprehension, so this line is a SyntaxError:
# [y for n in range(5) if y := n * n > 3] # SyntaxErrorEven in places where the grammar would accept it, the operator := has very low precedence. The text y := n * n > 3 would bind y to the comparison result (True or False), not to the square. The parentheses make y hold the number and let the comparison use it.
Using the walrus in dict and set comprehensions
The same technique works in every comprehension form, because the if clause is identical in all of them. In a dict comprehension, the bound name can appear in the key, the value, or both:
even_squares = {n: sq for n in range(5) if (sq := n * n) % 2 == 0}
print(even_squares) # {0: 0, 2: 4, 4: 16}In a set comprehension, remember that duplicates collapse after the output is computed:
words = ["apple", "kiwi", "banana", "fig", "cherry"]
long_lengths = {size for w in words if (size := len(w)) > 4}
print(long_lengths) # {5, 6}A common real-world use is a filter that depends on a match object. A regular expression match is either a Match or None. You want to test it and then read its groups, and the walrus lets you do both without calling match twice:
import re
lines = ["id=7", "noise", "id=12", "id=x"]
pattern = re.compile(r"id=(\d+)")
ids = [int(m.group(1)) for line in lines if (m := pattern.fullmatch(line))]
print(ids) # [7, 12]A Match object is truthy and None is falsy, so the bare (m := ...) works as a condition. Items that do not match are dropped, and m holds the match for the items that remain.
The binding leaks to the enclosing scope
An earlier chapter showed that a comprehension's loop variable does not leak. The walrus target behaves differently. A name bound with := inside a comprehension is bound in the scope that contains the comprehension, not in the comprehension's own scope. This is deliberate, and it is a documented exception in the language rules.
results = [y for n in range(5) if (y := n * n) > 3]
print(results) # [4, 9, 16]
print(y) # 16The loop variable n stays private, while y remains available afterward. Its value is the last one assigned. That last assignment happened for n = 4, the final item. Note that it is the last item tested, not the last item that passed the filter. In this example both are 16, but they can differ. If the final item fails the filter, y still holds that failing item's value.
The leak also makes running state possible, which is both a feature and a hazard:
total = 0
running = [total := total + n for n in range(5)]
print(running) # [0, 1, 3, 6, 10]
print(total) # 10This works, but it makes the comprehension depend on a variable that it also modifies. For running totals, itertools.accumulate states the intent directly:
from itertools import accumulate
print(list(accumulate(range(5)))) # [0, 1, 3, 6, 10]Restrictions you will run into
Python blocks several uses of := in comprehensions, because they would be confusing or ambiguous. All of these are errors at compile time:
- You cannot rebind the comprehension's own iteration variable.
[i := 0 for i in range(3)]is aSyntaxError. - You cannot use
:=in the iterable expression (the part afterin).[x for x in (data := range(3))]is aSyntaxError. - You cannot use
:=in a comprehension inside a class body.
If you hit one of these, bind the value before the comprehension on its own line, or restructure the code.
Alternatives, and when each fits
The walrus is not the only way to avoid duplicate work. Pick the option that reads best for your case.
| Approach | Calls per item | Python version | Notes |
|---|---|---|---|
| Compute twice | 1 to 2 | Any | Simple, but wasteful or wrong for impure functions |
| Walrus in the `if` clause | 1 | 3.8+ | Compact; the name leaks to the enclosing scope |
| Inner `for y in [expr]` | 1 | Any | Works on old versions; reads as a trick |
| Helper function or plain loop | 1 | Any | Best when the logic is more than one short condition |
The inner-loop trick adds a second for clause that iterates over a one-item list, which binds the name without :=:
results = [y for n in range(5) for y in [n * n] if y > 3]
print(results) # [4, 9, 16]It runs on any Python 3 version and keeps the name inside the comprehension, so nothing leaks. The cost is that readers must recognize the idiom.
When the computation is more involved, a plain loop is clearer than a long comprehension:
results = []
for n in range(5):
y = n * n
if y > 3:
results.append(y)
print(results) # [4, 9, 16]Generator expressions and laziness
The walrus also works in generator expressions, but evaluation is delayed. The name is bound only when the generator is advanced, not when it is created. Pass the generator to a consumer such as sum or list, or loop over it, and the bindings happen then:
gen = (sq for n in range(5) if (sq := n * n) > 3)
print(list(gen)) # [4, 9, 16]If you create the generator and then read sq before consuming it, the name does not exist yet. For that reason, avoid relying on the leaked name with generators. Use the name only inside the expression.
Summary of the rules
- Write
(name := expression)in theifclause, and usenamein the output expression. - Always parenthesize the walrus in a comprehension filter.
- The
ifclause runs before the output expression, so the binding must come first. - The target name leaks to the enclosing scope, and the loop variable does not.
- Choose a loop or helper when the comprehension becomes hard to read.
Exercise
What does the following code print, and why does y have the value it has afterward?
results = [y for n in range(3) if (y := n + 1) > 1]
print(results)
print(y)
Show answer
It prints [2, 3] and then 3. For n = 0, y is 1, which fails the test y > 1, so the item is dropped. For n = 1, y is 2 and for n = 2, y is 3, and both pass, so results is [2, 3]. The name y is bound in the enclosing scope, not inside the comprehension, so it is still available afterward. It holds the value from the last item tested, which is 3.
Exercise
A teammate writes [i := 0 for i in range(3)] to reset a counter. What happens when Python compiles it, and what would you do instead?
Show answer
Python raises a SyntaxError, because an assignment expression cannot rebind the comprehension's own iteration variable. If you want a list of zeros, write [0 for _ in range(3)] or [0] * 3, which is safe for immutable values like integers. If you need a counter outside the comprehension, bind it before the comprehension on its own line.
Exercise
Rewrite this comprehension so that parse(line) is called only once per line. Assume parse returns None for invalid lines: [parse(line) for line in lines if parse(line) is not None].
Show answer
[result for line in lines if (result := parse(line)) is not None]. The walrus in the if clause calls parse once, binds the value to result, and tests it against None. The output expression then reuses result. The parentheses are required around the assignment expression.