What's the walrus operator (`:=`), and when should you use it?
Quick Answer
The walrus operator (`:=`, PEP 572, Python 3.8+) assigns a value to a name **as part of a larger expression**, letting you both compute and bind a value in a single line — most commonly inside a `while` condition, an `if` condition, or a comprehension, to avoid computing the same expression twice.
Detailed Answer
The problem it solves: avoiding duplicate computation
# Without walrus -- compute the expensive call twice, or restructure the loop
data = get_next_chunk()
while data:
process(data)
data = get_next_chunk()
# With walrus -- compute once, inline in the condition
while (data := get_next_chunk()):
process(data)
Common use cases
In if conditions, to avoid computing something twice:
if (match := re.search(pattern, text)):
print(match.group())
Without :=, you'd write match = re.search(...) on its own line, then
if match: — walrus collapses that into one line while keeping match
available in the following block.
In comprehensions, to avoid recomputing an expensive filter/transform:
results = [y for x in data if (y := expensive(x)) is not None]
Without walrus, expensive(x) would need to be called twice — once for the
filter, once for the output expression — or the comprehension would need
to be restructured into a loop.
Syntax rules and gotchas
- Must be parenthesized in most contexts:
while (data := f()):(barewhile data := f():is actually valid too since it's the top-level statement condition, but parens are recommended for clarity). - It's an expression, not a statement —
x := 5alone is invalid, butprint(x := 5)is fine. - The scoping is the same as regular assignment (not a new scope) — inside a comprehension, the walrus-assigned name leaks into the enclosing scope, not the comprehension's own scope, which is a deliberate PEP 572 design choice (unlike the loop variable, which stays scoped to the comprehension).
Interview-ready summary: := assigns and evaluates in one expression,
primarily useful in while/if conditions and comprehensions to avoid
calling the same expensive expression twice. It's a readability/efficiency
tool, not a new capability — anything written with := can be rewritten
with an extra assignment statement.