:= Walrus operator

Last updated: 2026-09-22

:= Walrus operator

:= (PEP 572) assigns a value as part of an expression and returns it.

CategoryOperators
KindOperator
Python Version3.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.
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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏