typestar

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

  1. := binds and evaluates in one place.
  2. It shines in a while loop reading until a sentinel.
  3. Used anywhere else it usually hurts readability.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Expressions, step 65 of 72 in Language basics.

← Previous Next →