:=
The walrus: bind a name inside an expression — compute once, test, and reuse.
Common call
if (n := len(data)) > 10:
Returns
the assigned value, usable immediately
Replaces
compute-then-test without a setup line
Watch out
as a statement, plain = is correct — the walrus needs an expression context
(name :=expression)
→ Any
Operands
| Name | Type | Required | Description |
|---|---|---|---|
| name | identifier | yes | The variable to bind — a plain name only, no attributes or subscripts. |
| expression | Any | yes | Evaluated once; its value is both bound and returned. |
Return value
Any — The value of the expression — which is also bound to name in the enclosing scope. Assignment that IS an expression.
Common patterns
Test and reuse
The motivating case — no duplicate call, no throwaway line.
if (match := pattern.search(line)) is not None: print(match.group(1))
Read-until loops
Replaces the while-True-read-break dance.
while (chunk := file.read(8192)): process(chunk)
Reuse inside a comprehension
Compute an expensive value once per item.
results = [y for x in data if (y := f(x)) > 0]
Examples
1. Assign and test
if (n := 11) > 10:
print(n)
Returns
11 printed — n is bound2. Loop condition
while (line := input()) != "quit":
handle(line)
Returns
reads until "quit"Pitfalls
1. Not a statement replacement
Where a plain assignment works, the walrus is noise (and sometimes a SyntaxError without parens).
Noise
(x := 5) # as a whole statement
legal but pointless — use x = 5
Fix
x = 5
plain assignment
2. Scope leaks out of comprehensions
Unlike the loop variable, a walrus-bound name escapes to the enclosing scope.
Leaks
[y for x in data if (y := f(x)) > 0] print(y) # last value — defined!
y exists after the comprehension
Be aware
avoid reusing the name outside, or del it
explicit hygiene
3. Readability cuts both ways
Nesting walruses or using them where nothing is reused hurts more than it helps.
Dense
if (a := f()) and (b := g(a)) and (c := h(b)):
three assignments hidden in a condition
Spread it out
a = f() if a: b = g(a) ...
boring and clear
When to use
Use it
- Test-and-use: regex matches, reads, computed lengths
- Loop conditions that produce the loop value
- Avoiding double computation in comprehensions
Reach for something else
- Plain assignments → =
- Anything that gets harder to read — the walrus is optional sugar
Notes
Complexity
O(1) — an assignment
Return
the assigned value
CPython impl
NAMED_EXPR in the grammar; compiles to a store + load
Memory
No allocation
Thread-safe
Same as any assignment
FAQ
Tilt your head: := looks like a walrus’s eyes and tusks. The official name is "assignment expression" (PEP 572).
History
3.8
Introduced by PEP 572 — famously the controversy that preceded Guido’s retirement as BDFL.