← Back to Python, page 3

python-0051 · Medium mid

What is the walrus operator (:=), and where does it make code clearer?

The assignment expression name := value assigns and returns a value inside an expression. It avoids computing something twice in a condition, reading in a while loop, or repeating a call in a comprehension filter. Use it where it shortens code without hiding logic.

Full answer
python
import re
data = iter(["10", "20", "", "30"])
total = 0
while (line := next(data)) != "":
    total += int(line)
print(total)

codes = ["A-12", "bad", "B-7"]
print([int(m.group(1)) for c in codes if (m := re.fullmatch(r"[A-Z]-(\d+)", c))])

def expensive(x):
    print("computing", x)
    return x * x
values = [1, 5, 3]
print([y for x in values if (y := expensive(x)) > 5])

Output:

text
30
[12, 7]
computing 1
computing 5
computing 3
[25, 9]

The loop reads values until an empty string appears, without a separate read before the loop and another at the end. In the comprehension, the regex match is stored in m and reused, instead of matching twice. The last example calls expensive once per item while both filtering and returning the result. Overuse makes code dense; avoid nesting several walruses or using them where a normal assignment on its own line reads better.

python
import re
data = iter(["10", "20", "", "30"])
total = 0
while (line := next(data)) != "":
    total += int(line)
print(total)

codes = ["A-12", "bad", "B-7"]
print([int(m.group(1)) for c in codes if (m := re.fullmatch(r"[A-Z]-(\d+)", c))])

def expensive(x):
    print("computing", x)
    return x * x
values = [1, 5, 3]
print([y for x in values if (y := expensive(x)) > 5])

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Assigns inside expressions
  • Avoids repeated computation
  • Useful in while loops and filters
  • Keep usage simple

Common mistakes

  • Using := where plain assignment is clearer
  • Forgetting parentheses around the walrus in conditions

Follow-ups

  • What scope does a walrus target in a comprehension have?
  • Which Python version added it?

Tips

  • Show the repeated-computation case