Sub topic 15
The walrus operator :=
This chapter assumes you know how to write if and while statements, how to build list comprehensions, and how ordinary assignment with = works.
What it does
The walrus operator := is an assignment expression. It binds a value to a name and also produces that value, so you can use it inside a larger expression. Plain = is a statement and produces nothing.
data = [1, 2, 3]
if (count := len(data)) > 2:
print(f"{count} items")
print(count)Python computes len(data) once, stores it in count, and compares the result to 2. The name stays available after the if, so the last line prints 3.
Where it helps
Use it when you would otherwise compute a value twice, or compute it before a condition only to test it.
Loops that read until a stop value
lines = iter(["alpha", "beta", "", "gamma"])
while (line := next(lines, "")) != "":
print(line.upper())The loop prints ALPHA and BETA, then stops at the empty string. Without :=, you would need a priming call to next before the loop and a second call at the end of each pass.
Comprehension filters
import re
words = ["a1", "bb", "c3"]
digits = [m.group() for w in words if (m := re.search(r"\d", w))]
print(digits)This prints ['1', '3']. The filter runs the search once, and the result expression reuses the match. A match object is truthy and None is falsy, so the if skips words without a digit.
Common errors
- A bare
x := 5as a statement is aSyntaxError. Writex = 5, or wrap it as(x := 5)if you need the value. - The target must be a plain name.
d["k"] := 1andobj.attr := 1are not allowed. - Parentheses matter because
:=has the lowest precedence of all operators. Inif n := len(data) > 2,nis bound to the booleanTrueorFalse, not to the length. - Inside a comprehension, the name is bound in the enclosing scope. After the example above,
mstill exists and holds the last match, which was for"c3". - Do not use it where plain
=is clearer. If the value is used only once, a separate assignment line is easier to read.
Exercise
What does this code print, and why? values = [4, 9, 16] then if (n := len(values)) > 5: print("big") then print(n)
Show answer
It prints only 3. The condition 3 > 5 is false, so "big" is not printed. The name n was still bound to 3 by the walrus operator, and it remains available after the if.
Exercise
Rewrite if n := len(values) > 2: so that n holds the length instead of a boolean.
Show answer
if (n := len(values)) > 2:. Without parentheses, := has the lowest precedence, so it binds n to the result of the whole comparison, len(values) > 2.