:= — Assignment expression (walrus)
Bind an identifier to the value of an expression and produce that same value. Introduced in Python 3.8. The target must be a name, not an attribute, subscript or unpacking target. Parentheses are mandatory in several contexts, including a standalone expression statement and a comprehension filter. The operator binds less tightly than comparisons; use (size := len(items)) > limit to capture the size rather than a Boolean. Inside comprehensions the target belongs to the containing scope, subject to global/nonlocal declarations and restrictions against rebinding iteration variables or using named expressions in iterable clauses. Prefer a separate assignment if inline binding reduces readability.
Formal Syntax & Structure
(name := expression)if name := expression: suitewhile name := expression: suiteParameters & Attributes
| Name | Type | Description |
|---|---|---|
| name | identifier | Name to bind or rebind. |
| expression | object-producing expression | Evaluated once when the named expression executes. |
Return Value
The exact object produced by the right-hand expression, also bound to the target name.
Working Example
items = ["pen", "book", "bag"]if (size := len(items)) >= 3: print("bulk", size)values = [1, 3, 5]squares = [square for n in values if (square := n * n) > 4]print(squares)print(square)