Walrus Operator (:=)
Also Known As
:= operator
walrus
named expression
assignment expression
TL;DR
The assignment expression operator (Python 3.8+) — assigns a value while also using it in an expression, eliminating repeated computations in while loops and comprehensions.
Explanation
The walrus operator := allows assignment inside expressions. Use cases: while loops that compute a value to test and use (while chunk := file.read(8192)), list comprehensions filtering based on an expensive computation, and avoiding repeated function calls. It is a named expression — the value is available after the expression. Overuse makes code hard to read; limit to cases where repeating the call would be expensive or verbose.
Common Misconception
✗ The walrus operator replaces regular assignment — := is only valid inside expressions (in conditions, comprehensions); regular = for standalone assignments is still the standard.
Why It Matters
Without walrus, while loops often call a function twice — once to check and once to use. The walrus operator eliminates the duplication while keeping the code readable.
Common Mistakes
- Using := in simple cases where a regular assignment is clearer.
- Walrus in complex nested expressions — deeply nested := destroys readability.
- Not knowing that := variable scope leaks out of comprehensions (unlike regular comprehension variables).
- Using := instead of refactoring — sometimes extracting to a function is cleaner.
Code Examples
✗ Vulnerable
# Repeated call without walrus:
while True:
chunk = file.read(8192)
if not chunk:
break
process(chunk)
# Repeated expensive call in comprehension:
results = [expensive(x) for x in data if expensive(x) > threshold]
✓ Fixed
# Walrus operator — assign and test in one:
while chunk := file.read(8192):
process(chunk) # chunk already assigned, loop exits when empty
# Comprehension without repeated call:
results = [y for x in data if (y := expensive(x)) > threshold]
# Regex match with walrus:
if m := re.search(r'(\d+)', text):
print(m.group(1)) # m available without second search
References
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
16 Mar 2026
Edited
22 Mar 2026
Views
23
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 0
No pings yet today
No pings yesterday
Amazonbot 8
Perplexity 4
Unknown AI 3
Ahrefs 2
Google 1
Also referenced
How they use it
crawler 17
pre-tracking 1
Related categories
⚡
DEV INTEL
Tools & Severity
🟢 Low
⚙ Fix effort: Low
⚡ Quick Fix
Use := (walrus) to assign and test in one expression inside while loops and comprehensions — while chunk := file.read(8192) reads until empty without repeating the read call
📦 Applies To
python 3.8
web
cli
🔗 Prerequisites
🔍 Detection Hints
while True: x = fn(); if not x: break pattern; repeating function call in list comprehension condition and value
Auto-detectable:
✓ Yes
ruff
pylint
⚠ Related Problems
🤖 AI Agent
Confidence: Low
False Positives: High
✗ Manual fix
Fix: Low
Context: Function