Skip to content

Python walrus operator (:=): assign inside expressions (3.8)

  • What an assignment expression name := expr evaluates to and where it binds name.
  • The three idioms it was designed for: test-and-use, read-until-empty loops, and reusing a value inside a comprehension.
  • Why if n := f() > 2 does not do what it looks like, and where parentheses are required.
  • The special scope rule for comprehensions, and the forms that are a SyntaxError.
  • When two plain statements are clearer than one walrus.

The assignment expression name := expression, nicknamed the walrus operator, was added in Python 3.8 by PEP 572. It evaluates the expression, binds the result to name and returns the same value, so you can compute something once and both test and reuse it. The target must be a plain name; there is no obj.attr := or items[0] :=.

Many checks follow a “compute, test, use” shape. In OrdersPortal, the support inbox scans customer messages for an order reference. Without :=, the match must be computed on its own line before the if, which splits one idea in two and is easy to get wrong in loops (forgetting to recompute at the end of a while body is a classic bug).

Running the samples: each sample is a complete script. Save it as a .py file and run it with Python 3.14 (python3 sample.py); every sample also runs on 3.8 or later unless marked. The outputs shown were produced with CPython 3.14.6.

import re
ORDER_REF = re.compile(r"order (A-\d+)")
messages = ["Where is order A-1001?", "Hello", "Cancel order A-1002 please"]
# Before: compute, then test, on two lines.
for text in messages:
match = ORDER_REF.search(text)
if match:
print("before:", match.group(1))
# After: bind the match and test it in one expression.
for text in messages:
if match := ORDER_REF.search(text):
print("after: ", match.group(1))

Output:

before: A-1001
before: A-1002
after: A-1001
after: A-1002

The gain is small in an if, larger in a while loop and largest in a comprehension, where there is no other place to put a statement.

import io
# The value of (name := expr) is the value of expr.
print((total := 49.0 * 2) + 1, total)
# Precedence: := binds more loosely than comparisons.
def count_items():
return 3
if n := count_items() > 2:
print("without parentheses n is", n)
if (n := count_items()) > 2:
print("with parentheses n is", n)
# while loops: read a stream in fixed-size chunks
stream = io.BytesIO(b"A-1001,A-1002,A-1003")
while chunk := stream.read(8):
print(chunk)
# In a comprehension, the target is bound in the enclosing scope.
prices = [19.5, 49.0, 120.0, 5.0]
expensive = [p for p in prices if (with_tax := round(p * 1.2, 2)) > 50]
print(expensive, with_tax) # with_tax holds the LAST value computed
# Capture a "witness" from any()
order_ids = ["A-1001", "B-77", "A-1003"]
if any((bad := oid).startswith("B-") for oid in order_ids):
print("first non-A order:", bad)

Output:

99.0 98.0
without parentheses n is True
with parentheses n is 3
b'A-1001,A'
b'-1002,A-'
b'1003'
[49.0, 120.0] 6.0
first non-A order: B-77

The rules behind that output:

  • Value and binding. (total := 49.0 * 2) binds total to 98.0 and the whole expression is 98.0, so adding 1 prints 99.0.
  • Lowest precedence of any expression operator. n := count_items() > 2 parses as n := (count_items() > 2), so n is True. Parenthesize the assignment when you compare its result.
  • No new scope. The name is bound in the current function, module or class body, exactly like =. It stays defined after the if or while.
  • Comprehensions are the exception. A := inside a list, set or dict comprehension or a generator expression binds the name in the enclosing scope, not the comprehension’s private one. That is why with_tax is readable after the comprehension (holding the last value computed, 6.0), and why any() can leave behind the first matching element. Ordinary comprehension loop variables such as p still do not leak.
  • while with := replaces “priming reads”. The loop stops when stream.read(8) returns the falsy b"".

Where parentheses are required, and what is never allowed

Section titled “Where parentheses are required, and what is never allowed”

The language reference requires parentheses when := is used as an expression statement, and inside slicing, conditional expressions, lambdas, keyword arguments, comprehension if clauses, and assert, with and assignment statements. They are not required at the top of an if or while condition. Since Python 3.10 they are also optional in set literals, set comprehensions and sequence indexes (but not slices).

Some forms are rejected by the compiler outright:

snippets = {
"statement": "y := 10",
"rhs of =": "x = y := 10",
"keyword arg": "print('a', sep=s := ', ')",
"attribute target": "if (self.total := 10): pass",
"rebind loop var": "[i := i + 1 for i in range(3)]",
"in iterable": "[x for x in (data := [1, 2])]",
}
for label, src in snippets.items():
try:
compile(src, "<demo>", "exec")
print(f"{label:17} OK")
except SyntaxError as exc:
print(f"{label:17} SyntaxError: {exc.msg}")

Output:

statement SyntaxError: invalid syntax
rhs of = SyntaxError: invalid syntax
keyword arg SyntaxError: invalid syntax
attribute target SyntaxError: cannot use assignment expressions with attribute
rebind loop var SyntaxError: assignment expression cannot rebind comprehension iteration variable 'i'
in iterable SyntaxError: assignment expression cannot be used in a comprehension iterable expression

The first three are valid once parenthesized ((y := 10), x = (y := 10), sep=(s := ', ')), though PEP 572 itself calls them discouraged style. The last three are invalid in any form: the target must be a name, it cannot rebind a comprehension’s for variable, and it cannot appear in a comprehension’s iterable expression.

OrdersPortal accepts pasted order lines such as KB-101 x2 @ 49.00. The parser skips blanks and comments, rejects lines that do not match, applies a per-SKU discount when one exists, and reports lines whose total is at least 100. Each := removes a recomputation or a separate “look up, then test” statement.

import re
from decimal import Decimal
LINE = re.compile(r"(?P<sku>[A-Z]{2}-\d{3}) x(?P<qty>\d+) @ (?P<price>\d+\.\d{2})")
DISCOUNTS = {"KB-101": Decimal("0.10")}
def parse_order(lines: list[str]) -> dict:
items, rejected = [], []
for raw in lines:
if not (text := raw.strip()) or text.startswith("#"):
continue # skip blanks and comments
if (m := LINE.fullmatch(text)) is None:
rejected.append(text)
continue
qty, price = int(m["qty"]), Decimal(m["price"])
if (rate := DISCOUNTS.get(m["sku"])) is not None:
price -= (price * rate).quantize(Decimal("0.01"))
items.append((m["sku"], qty, price))
# Compute each line total once; keep only lines worth reviewing.
big = [(sku, t) for sku, q, p in items if (t := q * p) >= 100]
return {"items": items, "big_lines": big, "rejected": rejected}
result = parse_order([
"# OrdersPortal order A-1001",
"KB-101 x2 @ 49.00",
"",
"MS-220 x1 @ 19.50",
"HD-330 x4 @ 35.25",
"gift wrap please",
])
for key, value in result.items():
print(key, value)

Output:

items [('KB-101', 2, Decimal('44.10')), ('MS-220', 1, Decimal('19.50')), ('HD-330', 4, Decimal('35.25'))]
big_lines [('HD-330', Decimal('141.00'))]
rejected ['gift wrap please']

Note (rate := DISCOUNTS.get(...)) is not None: comparing explicitly with None keeps a legitimate falsy value (a Decimal("0") rate) from being skipped. The comprehension [(sku, t) ... if (t := q * p) >= 100] computes each total once and uses it both in the filter and in the result, which would otherwise need a nested generator or a loop.

  • Missing parentheses around a comparison. if n := len(items) > 10 binds a bool. Write if (n := len(items)) > 10.
  • Testing truthiness when 0, "" or an empty list is valid. while chunk := read() is right for bytes; for values where zero is meaningful, compare with is not None.
  • Assuming the comprehension target is private. := inside a comprehension overwrites a variable of the same name in the enclosing function, and after the comprehension it holds the last value computed (or is unbound if nothing ran).
  • Chaining several walruses in one condition. if (a := f()) and (b := g(a)) and (c := h(b)): is legal but hard to debug; separate statements with early return or continue read better.
  • Using it as a shorter =. A top-level (x := 5) statement works but adds nothing; PEP 572 deliberately makes the unparenthesized form a syntax error so there is one obvious way.
  • Trying to assign to attributes or items. (self.total := 0) and (row[0] := 1) are syntax errors; only names can be targets.

Use := when a value is computed once, tested immediately and then used again, and when the alternative is a duplicated call or a statement wedged awkwardly before a loop or inside a comprehension.

Situation Prefer
Test a regex match, then use it if m := pattern.search(s):
Loop until a read returns empty while chunk := f.read(n):
Filter and keep a computed value in a comprehension [y for x in xs if (y := f(x)) is not None]
Value used in several later statements A normal = assignment
Condition that needs three or more bindings Separate statements with early continue or return
Code that must run on Python 3.7 or older A normal = assignment

Assignment expressions are available in Python 3.8 and later, including 3.14. Two later releases relaxed the rules: Python 3.10 allows them unparenthesized in set literals, set comprehensions and sequence indexes; Python 3.12 allows assigning to a name that appears in a comprehension’s target only as part of an attribute or subscript (for example b in for a, b.prop in it). Linters and formatters that target older versions will flag := as a syntax error.

1. What does print((x := 3) * 2, x) print, and why? 6 3. The assignment expression binds x to 3 and evaluates to 3, which is then multiplied by 2. The binding happens before x is read as the second argument because arguments are evaluated left to right.

2. Why is if n := len(items) > 10: a bug? := has lower precedence than comparisons, so n receives the result of len(items) > 10, a bool. Parenthesize the assignment: if (n := len(items)) > 10:.

3. Where does a := inside a list comprehension bind its name? In the scope that contains the outermost comprehension, not the comprehension’s own scope. That lets you capture a witness from any() or a running total, but it also means it can overwrite a same-named local. It cannot rebind the comprehension’s for variable.

4. Senior scenario: a code review shows a 15-line validation function rewritten as one condition with five chained walrus assignments. Coverage is unchanged and tests pass. Do you approve it? Usually not. Measure the change against readability and debuggability: one condition with five bindings gives a single line in tracebacks and coverage reports, hides which step failed, and couples every step into one boolean. Ask for the original shape with early returns, keeping := only where it removes a duplicated call (for example if (m := pattern.match(s)) is None: return error). Agree a team guideline (for example “at most one := per condition, never in a statement position”) so the discussion does not repeat in every review.

  • name := expr (Python 3.8) binds name and evaluates to the value of expr.
  • It has the lowest expression precedence: parenthesize it whenever you compare its result.
  • It binds in the current scope; inside a comprehension, in the enclosing scope.
  • The target must be a plain name, and several positions (statement level, keyword arguments, comprehension iterables) reject it.
  • Use it for test-and-use, read loops and comprehension filters; use plain statements everywhere else.