Walrus Operator (:=)
The walrus operator (:=) in Python is an assignment expression operator added in Python 3.8. Unlike a regular assignment statement (=), it returns a value as an "expression" while simultaneously assigning to a variable. It allows binding a computed result to a variable inside a conditional expression, eliminating the redundancy of writing the same expression twice.
Syntax
# Basic syntax: assign to a variable while returning a value as an expression.
variable := expression
# Assignment in while condition (use the read result directly as the loop condition)
while (variable := expression):
# processing using variable
# Assignment in if condition (use the match result inside the block)
if (variable := expression):
# processing using variable
# Use in the condition clause of a list comprehension (limit computation to one call)
[variable for x in iterable if (variable := expression)]
Keywords Reference
| Syntax Pattern | Notes |
|---|---|
| variable := expression | An assignment expression operator that evaluates the expression, assigns the result to a variable, and returns the value. Available from Python 3.8 onward. |
| while (variable := expression): | Determines loop continuation from the return value of the expression while simultaneously assigning the result to a variable. |
| if (variable := expression): | Branches on the return value of the expression while assigning the result to a variable that can be reused inside the block. |
| [f(variable) for x in it if (variable := g(x))] | Uses an assignment expression in the condition clause of a comprehension to combine the condition check and value computation into one call. |
Sample Code
The most basic use of the walrus operator. Comparing the difference from a regular assignment statement.
walrus_basic.py
# A regular assignment statement (=) does not return a value and cannot be used in an expression. cursed_energy = 100 print(cursed_energy) # 100 # The walrus operator (:=) assigns and returns a value at the same time. # Assignment and print can be combined into one line. print(power := 9000) # 9000 print(power) # 9000 — the assigned value can be used later. # Enclosing in parentheses to make precedence explicit is the recommended style. result = (domain := "Infinite Void") + " — Limitless Cursed Technique" print(domain) # Infinite Void print(result) # Infinite Void — Limitless Cursed Technique
python3 walrus_basic.py 100 9000 9000 Infinite Void Infinite Void — Limitless Cursed Technique
Using an assignment expression in the condition of a while loop. Pops elements from a list one by one and exits the loop when None is encountered.
walrus_while.py
# Processing a mission queue for cursed spirit exorcism in order.
# Without the walrus operator: pop() needs to be called twice or a flag is required.
missions = ["Exorcise Hanami", "Exorcise Mahito", "Exorcise Jogo", None]
# With the walrus operator: extraction and condition check happen simultaneously in one line.
while (mission := missions.pop(0)) is not None:
print(f"Executing mission: {mission}")
print("All missions complete")
python3 walrus_while.py Executing mission: Exorcise Hanami Executing mission: Exorcise Mahito Executing mission: Exorcise Jogo All missions complete
Using an assignment expression in an if condition. The regex match result is used directly inside the block. Without the walrus operator, two lines are needed: one for the match and one for the None check.
walrus_if.py
import re
# Processing a list of strings containing sorcerer technique information.
records = [
"Itadori Yuji: Divergent Fist output=5000",
"Megumi Fushiguro: Ten Shadows Technique output=unknown",
"Nobara Kugisaki: Straw Doll Technique output=2800",
"Gojo Satoru: no data",
]
pattern = re.compile(r"output=(\d+)")
for record in records:
# Without walrus operator:
# m = pattern.search(record)
# if m:
# print(...)
# With walrus operator, the if fits in one line.
if (m := pattern.search(record)):
print(f"Output detected: {m.group(1)}")
else:
print(f"No output: {record.split(':')[0]}")
python3 walrus_if.py Output detected: 5000 No output: Megumi Fushiguro Output detected: 2800 No output: Gojo Satoru
Using an assignment expression in the condition clause of a list comprehension. Avoids calling an expensive function twice for both the condition check and value retrieval.
walrus_comprehension.py
# Simulating a heavy computation that analyzes cursed spirits.
def analyze_curse(curse_name):
"""Analyzes a cursed spirit and returns its cursed energy value (None on failure)."""
data = {
"Hanami": 8500,
"Mahito": 9200,
"Jogo": 9000,
"Dagon": 8800,
}
return data.get(curse_name) # returns None if not in the dict.
curses = ["Hanami", "Unknown A", "Mahito", "Unknown B", "Jogo", "Dagon"]
# Without walrus operator: analyze_curse() is called twice.
# results = [analyze_curse(c) for c in curses if analyze_curse(c) is not None]
# With walrus operator: analyze_curse() is called only once.
results = [
power
for c in curses
if (power := analyze_curse(c)) is not None
]
print(results) # [8500, 9200, 9000, 8800]
python3 walrus_comprehension.py [8500, 9200, 9000, 8800]
Notes
With the walrus operator (:=), limiting where it is used is important. It is effective in cases where "assigning while performing a condition check" reads naturally — for example, while loops that read data, or if statements that reuse a regex match result. On the other hand, forcing the walrus operator into a simple assignment can confuse readers who wonder why an assignment expression is being used there.
Using it in list comprehensions is most effective when a computationally expensive function is used for both the condition and the value. For low-cost operations, writing a simple if clause is more readable. See also list comprehensions.
The walrus operator is only available in Python 3.8 and later. It cannot be used when compatibility with earlier versions is required. It is best understood after learning the basics of while loops and if statements.
Common Mistakes
Using it as a top-level assignment statement and getting a SyntaxError
The walrus operator cannot be used as a standalone statement. It can only be used inside an expression.
walrus_toplevel_ng.py
# NG pattern: using it as a top-level assignment (name := "Itadori Yuji") # not a SyntaxError, but should not be used as a plain assignment
walrus_toplevel_ok.py
# OK pattern: use inside a condition or comprehension data = [1, 15, 3, 22, 8] filtered = [y for x in data if (y := x * 2) > 10] print(filtered) # [30, 44, 16]
[30, 44, 16]
Forgetting parentheses and falling into operator precedence traps
The walrus operator has low precedence, similar to assignment operators. Parentheses may be required when combining it with comparison operators.
walrus_paren_ng.py
scores = [85, 42, 91, 67] # NG pattern: missing parentheses # while score := scores.pop() > 60: is interpreted as (while score := (scores.pop() > 60)) # a bool value ends up assigned to score
walrus_paren_ok.py
scores = [85, 42, 91, 67]
# OK pattern: make precedence explicit with parentheses
while scores and (score := scores.pop()) > 60:
print(f"High score: {score}")
High score: 67 High score: 91
Using it on Python 3.7 or earlier and getting a SyntaxError
The walrus operator (:=) is syntax added in Python 3.8. It causes a SyntaxError in environments running 3.7 or earlier.
walrus_version.py
import sys
print(sys.version) # check version
# Only works on Python 3.8+
members = ["Itadori Yuji", "Megumi Fushiguro", "Nobara Kugisaki"]
if n := len(members):
print(f"{n} members found")
3.12.0 (main, ...) 3 members found
If you find any errors or copyright issues, please contact us.