The walrus operator in Python
Assign inside an expression, when the value is needed twice.
lines = iter(["first", "second", "", "third"])
while (line := next(lines, None)) is not None:
if not line:
print("blank line, stopping")
break
print(line)
values = [1, 2, 3, 4, 5, 6]
if (total := sum(values)) > 20:
print(f"total {total} is large")
print([squared for n in values if (squared := n * n) % 2 == 0])
How it works
:=binds and evaluates in one place.- It shines in a while loop reading until a sentinel.
- Used anywhere else it usually hurts readability.
Keywords and builtins used here
breakforifiternextprintsumwhile
The run, in numbers
- Lines
- 13
- Characters to type
- 314
- Tokens
- 111
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 67 seconds.
Step 1 of 3 in Expressions, step 65 of 72 in Language basics.