Sub topic 15
The walrus operator :=
This chapter assumes you know Python assignment with =, if and while statements, list comprehensions, and basic function calls. You should also know that an expression produces a value and a statement does not.
What the walrus operator does
The walrus operator := is an assignment expression. It binds a value to a name and also evaluates to that value, so you can assign inside a larger expression. It was added in Python 3.8 (PEP 572).
Plain = is a statement. It cannot appear inside a condition or a function call. := can.
data = [1, 2, 3]
if (count := len(data)) > 2:
print(f"{count} items")
print(count)The call len(data) runs once. Its result is bound to count, and the parenthesized expression evaluates to 3, which is then compared with 2. After the if, count is still defined, because := creates an ordinary variable in the current scope.
Without the walrus, you would write two lines:
data = [1, 2, 3]
count = len(data)
if count > 2:
print(f"{count} items")Both versions behave the same. The walrus version only saves a line and keeps the name next to the test that uses it.
Syntax rules
The target of := must be a plain name. You cannot assign to attributes, subscripts, or tuples this way.
# Each of these is a SyntaxError:
# obj.attr := 5
# items[0] := 5
# (a, b) := (1, 2)Unparenthesized := is not allowed at the top level of an expression statement. The parentheses are required there.
| Code | Valid? | Reason |
|---|---|---|
| `y := 5` | No | Unparenthesized at statement level |
| `(y := 5)` | Yes | Parenthesized |
| `y = (z := 5)` | Yes | Parenthesized on the right of `=` |
| `f(y := 5)` | Yes | Direct function argument |
| `f(key=y := 5)` | No | Not allowed in a keyword argument value without parentheses |
| `if (n := 10) > 5:` | Yes | Parenthesized inside a comparison |
| `if n := 10:` | Yes | Whole `if` condition |
The rule is easiest to remember like this: when in doubt, add parentheses. := has the lowest precedence of any operator, lower than comparisons, and, or, and the conditional expression. That is why (count := len(data)) > 2 needs the parentheses. Without them, count := len(data) > 2 would bind count to the boolean result of the comparison.
data = [1, 2, 3]
if (count := len(data)) > 2:
print(count)
if count2 := len(data) > 2:
print(count2)The first block prints 3. The second prints True, because count2 holds the result of len(data) > 2. This is the most common walrus mistake.
Use case 1: avoid computing twice
A common pattern is to compute a value, test it, then use it. Walrus lets you do all three without a separate line or a repeated call.
import re
text = "order id: 4821"
if (match := re.search(r"\d+", text)) is not None:
print(match.group())re.search returns a match object or None. The walrus binds the result so the body can use it. Here the parentheses around the assignment are required, and is not None is explicit so that a falsy-but-valid result would not be confused with "no match".
Use case 2: loops that read until done
Before the walrus, a loop that reads until a sentinel value often needed while True with a break, or a duplicated read before the loop.
import io
stream = io.StringIO("abcdefghij")
while chunk := stream.read(4):
print(chunk)This prints abcd, efgh, and ij. When read returns an empty string at the end, the condition is falsy and the loop stops. This relies on truthiness, covered earlier in this tutorial.
The older form needs more lines:
import io
stream = io.StringIO("abcdefghij")
while True:
chunk = stream.read(4)
if not chunk:
break
print(chunk)Use case 3: comprehensions
You can use := in a comprehension to compute a value once and use it both in the filter and in the output.
def expensive(n):
return n * n
numbers = [1, 2, 3, 4, 5]
results = [y for n in numbers if (y := expensive(n)) > 5]
print(results)This prints [9, 16, 25]. Each expensive(n) call happens once per item. Without the walrus you would call the function twice, or build an intermediate list.
Scope in comprehensions
A name bound with := inside a comprehension is bound in the enclosing scope, not in the comprehension's own scope. This differs from the loop variable n, which stays local to the comprehension.
numbers = [1, 2, 3]
squares = [last := n * n for n in numbers]
print(squares)
print(last)This prints [1, 4, 9] and then 9. The variable last leaks out and holds the final value.
Two restrictions apply:
- You cannot rebind the comprehension's own iteration variable with
:=. That raises aSyntaxError. - You cannot use
:=in the iterable expression of a comprehension.
Use case 4: short-circuit with `and` / `or`
The walrus works well with short-circuit operators because the assignment only runs if evaluation reaches it.
values = [10, 20, 30]
if values and (first := values[0]) > 5:
print(first)If values is empty, the right side never runs, so first is never assigned. Using first after the if in that case would raise NameError. This is a real gotcha: a walrus inside a short-circuited branch may leave the name unbound.
values = []
if values and (first := values[0]) > 5:
print(first)
print("first" in dir())This prints False.
Walrus versus `=`
| Feature | `=` | `:=` |
|---|---|---|
| Kind | Statement | Expression |
| Produces a value | No | Yes |
| Allowed inside conditions | No | Yes |
| Target | Names, attributes, subscripts, unpacking | Plain names only |
| Chained form | `a = b = 0` | Not chained directly |
| Needs parentheses | No | Often |
Because = and := have different jobs, they are not interchangeable. Use = for ordinary assignment. Reach for := only when the assignment must happen inside an expression.
When not to use it
Walrus can make code harder to read. Avoid it in these cases:
- When a separate assignment line is just as clear.
- When you pack several walruses into one condition.
- When the bound name is not used afterward.
- When the code would need confusing parentheses to be correct.
A practical test: if a reader has to stop and work out which parts evaluate and which names get bound, rewrite it as two statements.
# Hard to read
if (a := f()) and (b := g(a)) and (c := h(b)) > 0:
print(a, b, c)This works, but each name may be unbound if an earlier test fails, and the line mixes three jobs. Prefer separate statements with early exits.
Common errors
- Forgetting parentheses, so the name captures a boolean instead of the value.
- Using
:=where=is meant at statement level, which gives aSyntaxError. - Using a name after a short-circuited walrus that may never have run.
- Expecting a comprehension's walrus variable to stay inside the comprehension.
- Assigning to an attribute or subscript, which is not allowed.
Evaluation flow
Exercises
Exercise
What does this code print, and why? data = [4, 5, 6] if n := len(data) > 2: print(n)
Show answer
It prints True. Without parentheses, := has lower precedence than >, so n is bound to the result of len(data) > 2, which is True. Writing (n := len(data)) > 2 would print 3.
Exercise
Rewrite this loop with the walrus operator so it no longer needs break. lines = ["a", "b", ""] i = 0 while True: line = lines[i] i += 1 if not line: break print(line)
Show answer
Use an iterator and bind each item in the condition: it = iter(["a", "b", ""]) while line := next(it, ""): print(line) The loop prints a and b, then stops when the empty string is falsy.
Exercise
After this code runs, is the name first defined? Explain. values = [] if values and (first := values[0]) > 5: pass
Show answer
No. values is empty, so it is falsy and and short-circuits. The right side never runs, so first is never assigned. Reading first later raises NameError.