Skip to main content
The := operator, formally known as an assignment expression and colloquially as the “walrus operator,” evaluates an expression, binds the result to an identifier, and returns that value simultaneously. Introduced in Python 3.8 (PEP 572), it allows variable assignment to occur within contexts that strictly require expressions, distinguishing it from the standard = assignment operator, which is a statement.

Syntax

Mechanics and Behavior

Expression vs. Statement The fundamental difference between = and := lies in their return behavior. The standard assignment (=) is a statement; it performs the binding operation but evaluates to nothing. The assignment expression (:=) performs the binding operation and evaluates to the result of the right-hand expression.
Operator Precedence The := operator has the lowest precedence of all Python operators. Because of this, it frequently requires parentheses to ensure the expression is evaluated and bound correctly before surrounding operations take place.
Scope Rules Variables bound via the assignment expression are generally bound in the current local scope. However, when utilized inside comprehensions (list, set, or dict), the variable bound by := leaks into the enclosing scope. This contrasts with the standard iteration variables in comprehensions, which remain strictly isolated.

Syntactic Restrictions

Python enforces strict limitations on the := operator to prevent ambiguity in the parser:
  1. No Unparenthesized Top-Level Assignment: It cannot be used as a direct, unparenthesized replacement for = at the top level of a block.
x := 10 # SyntaxError (x := 10) # Valid
  1. No Inline Type Hinting: Type annotations cannot be combined directly with an assignment expression.
(x: int := 5) # SyntaxError