Python 3.8+Arithmetic & operatorsterm
Walrus operator :=
operators
The walrus operator (:=) assigns a value to a variable inside an expression (Python 3.8+). Handy in while conditions, in comprehensions and in if.
Syntax
variable := expression
The := operator binds more loosely than nearly everything else, so inside a condition it is almost always wrapped in parentheses: if (n := len(s)) > 10. It cannot replace a plain assignment statement — a bare line n := 10 is a SyntaxError. The real win is not brevity but computing a value once instead of calling the same function twice, in the test and again in the body.
Examples
data = [1, 2, 3, 4]
while chunk := data[:2]:
data = data[2:]
print(chunk) # → [1, 2], затем [3, 4]
nums = [1, -2, 3, -4]
pos = [y for x in nums if (y := x * 2) > 0]
print(pos) # → [2, 6]
s = "abcdef"
if (n := len(s)) > 3:
print(n) # → 6
if m := len(s) > 3:
print(m) # → True — без скобок в m попал результат сравнения
See also
Open in the full glossarydocs.python.orgReport an inaccuracy