:= Walrus operator
Last updated: 2026-09-22
:= Walrus operator
:= (PEP 572) assigns a value as part of an expression and returns it.
| Category | Operators |
|---|---|
| Kind | Operator |
| Python Version | 3.8+ |
📝 Syntax
name := value
▶ Example
Edit the code, press Run, and see the result in the output panel:
Output:
3.0
3.0
💡 Tip := is handy for reusing expensive computations in if / while conditions.
💡 Related Cases
More case studies coming soon — check back later.
❓ FAQ
QWhat is the difference between := and =?
A`:=` is an expression: it can assign a value inside a condition such as `if` or `while` and also return that value. `=` is a statement and cannot appear in an expression position. `if (x = 5):` is a syntax error, while `if (x := 5):` is valid.
QWhat Python version does := require?
APython 3.8+ (PEP 572). On 3.7 and below it raises `SyntaxError: invalid syntax`.
QWhat is the classic usage of :=?
ARead-and-test in a `while` loop: `while (line := f.readline()):` processes each line; or reuse an expensive computation in a condition: `if (root := math.sqrt(x)) > 2:` uses `root` directly.
QWhen should you not use :=?
ASkip it whenever you can. Plain assignment is clearer in most scenarios; overusing the walrus operator hurts readability. PEP 572 suggests using it only to avoid repeated computation and to make logic more compact.