Skip to content

Python Walrus Operator (:=)

The walrus operator := (introduced in Python 3.8, PEP 572) is an assignment expression: it assigns a value to a variable and returns that value, all in one expression. The name comes from its resemblance to a walrus’s eyes and tusks.

quickstart.py
# Without walrus: compute, store, then test
n = len("hello")
if n > 3:
    print(f"{n} characters")
 
# With walrus: assign and test in one line
if (n := len("hello")) > 3:
    print(f"{n} characters")
# 5 characters

Assignment statement vs assignment expression

Section titled “Assignment statement vs assignment expression”
= (statement):= (expression)
x = 5 stands alone.(x := 5) can sit inside a larger expression.
Returns nothing.Evaluates to the assigned value.
Can’t be used in if/while conditions.Designed exactly for that.

Wrap walrus expressions in parentheses in most contexts — it keeps intent clear and is required in several places.

Avoid duplicating the “read” both before and inside the loop.

while_loop.py
# Process items from an iterator until a sentinel (0) appears
data = [5, 8, 3, 0, 9]
it = iter(data)
 
while (value := next(it, 0)) != 0:
    print(value)
# 5
# 8
# 3

A classic real-world shape is reading chunks from a file or stream:

read_chunks.py
# Pseudocode pattern — read until there's nothing left
# while (chunk := file.read(1024)):
#     process(chunk)

Compute once, test, then reuse the captured value in the body.

if_capture.py
text = "hello world"
 
if (count := text.count("o")) > 1:
    print(f"Found 'o' {count} times")
# Found 'o' 2 times

Compute an expensive value once and both filter and keep it.

comprehension.py
numbers = [1, 2, 3, 4, 5, 6]
 
# Keep doubled values that exceed 5 — double() is computed once per item
result = [doubled for n in numbers if (doubled := n * 2) > 5]
print(result)   # [6, 8, 10, 12]

Without the walrus you’d compute n * 2 twice (once to filter, once to keep) or need a longer loop.

sketch The walrus stops you computing the same thing twice p5.js
A test and its result usually want the same value, and without an assignment expression you either compute it twice or restructure the loop around a temporary. Here the condition calls an O(n) helper and the body needs the same answer: recomputing took 1.65 milliseconds, naming it once with the walrus took 0.77, and both produced identical output. The saving is not a micro-optimisation -- it is proportional to whatever you were calling twice.
  • It’s not a plain = — you can’t write (x := 5) to replace a normal top-level assignment; just use x = 5 there.
  • Readability — overusing := makes lines dense. Reach for it when it removes duplication, not to win at code golf.
  • Parenthesesn := len(s) alone is a syntax error in many spots; write (n := len(s)).
  • Python 3.8+ only — older interpreters reject :=.
  • := assigns and returns a value, so it works inside expressions.
  • Great for while loops (read-and-test), if statements (capture-and-test), and comprehensions (compute once).
  • Always parenthesize it; use it to remove duplication, not to obscure code.
  • Requires Python 3.8+.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading