Python Walrus Operator (:=) Explained With 8 Real Examples
The Python walrus operator := assigns a value inside an expression, so you can compute something once and use it right away in an if, a while loop or a comprehension. Learn the eight patterns worth using, the scope and precedence rules, and when the walrus makes code worse, with tested output.
- The Python walrus operator
:=(assignment expression) arrived in Python 3.8 with PEP 572. - It assigns and returns a value, so you can test a result and keep it in one step.
- In our comprehension test it cut function calls from 15 to 10 by avoiding a repeated computation.
- It must be wrapped in parentheses in most places, and it is a syntax error as a plain statement.
Python code often computes a value, checks it, and then needs it again: the length of a list, a regex match, the next chunk of a file. Before Python 3.8 you either wrote an extra line or called the function twice. The Python walrus operator, :=, solves that by letting an assignment live inside an expression. It is named after its look: turn your head sideways and the colon and equals sign resemble a walrus’s eyes and tusks.
Every example below ran on Python 3.13.6 and shows its real output. If you are new to Python syntax, our Python tutorial for beginners is a good first stop.
What is the walrus operator?
A normal assignment, x = 5, is a statement: it does something but has no value, so you cannot put it inside an if condition. An assignment expression, (x := 5), both stores 5 in x and evaluates to 5, so it can appear anywhere an expression is allowed.
z = (w := 3) + 1
print(w, z) # 3 4
That small difference unlocks a handful of clean patterns, and a few traps, which we cover one by one.
Syntax and basic rules
(name := expression)
- The left side must be a plain name.
obj.attr := 1anditems[0] := 1are not allowed. - A bare walrus as a whole statement is rejected:
y := 5raisedSyntaxError: invalid syntax, while(y := 5)worked. - Parentheses are required in most positions and recommended everywhere for readability.
- It needs Python 3.8 or later. Code using it will not even parse on older versions.
Example 1: compute and test in an if
data = [3, 8, 1, 9, 4]
if (n := len(data)) > 3:
print(f"list is long: {n} items") # list is long: 5 items
print("n still available:", n) # n still available: 5
The length is calculated once, compared, and kept for the message. The variable stays available after the if, just like a normal assignment. This pattern is most useful when the value is expensive or when writing it twice would clutter the line.
Example 2: regex matches
import re
pattern = re.compile(r"order-(\d+)")
for line in ["ship order-42 today", "no id here", "order-7 delayed"]:
if (m := pattern.search(line)):
print("found", m.group(1))
# found 42
# found 7
This is the classic use case. search() returns a match object or None, and you need the object only when it exists. Without the walrus you would write the search on one line and the if on the next for every pattern. Our Python regex guide has more matching techniques.
Example 3: while loops that read until empty
chunks = iter([b"abc", b"de", b""])
def read():
return next(chunks)
parts = []
while (block := read()):
parts.append(block)
print("blocks read:", parts) # blocks read: [b'abc', b'de']
The older version needs while True:, a read, an if not block: break and then the real work. The walrus puts the read and the stop condition in one line. The same shape works for f.read(8192) on files, sock.recv() on sockets and paging through an API until an empty page comes back. See Python file handling for chunked reading.
Example 4: avoid repeated work in comprehensions
Suppose you want the results of a slow function, but only those above a threshold. We counted calls to see the difference:
def slow(x):
slow.calls += 1
return x * x
slow.calls = 0
nums = list(range(10))
res1 = [slow(x) for x in nums if slow(x) > 20] # calls slow twice
res2 = [y for x in nums if (y := slow(x)) > 20] # calls slow once
# without walrus: [25, 36, 49, 64, 81] calls 15
# with walrus: [25, 36, 49, 64, 81] calls 10
Same result, one third fewer calls. Without the walrus, the five kept items each call slow twice (once in the filter and once in the output), giving 15 calls. With it, every item is computed once. If slow were a database query or an API call, that difference would matter a lot. Comprehension basics are in our list comprehension guide.
Example 5: dictionary lookups
d = {"a": 1}
if (val := d.get("b")) is None:
print("missing key -> None") # missing key -> None
dict.get returns None for a missing key, so you can fetch and test in one step and keep the value for the happy path. Be careful when 0, an empty string or an empty list are valid values: compare with is None instead of relying on truthiness, as shown. More on lookups in our Python dictionary guide.
Example 6: running totals inside a comprehension
values = [1, 2, 3, 4]
total = 0
running = [total := total + v for v in values]
print(running) # [1, 3, 6, 10]
A walrus inside a comprehension assigns to the enclosing scope, so it can carry state from one item to the next. It is a neat trick, but itertools.accumulate(values) does the same job more clearly, so use this only when you need extra logic in each step.
Example 7: capturing the witness of any()
values = [1, 2, 3, 4]
any_big = any((hit := v) > 2 for v in values)
print("first > 2 witness:", hit) # first > 2 witness: 3
any() stops at the first match, and the walrus remembers which item triggered it. The same works with all() to capture the first item that failed a check, which makes error messages much more useful than a bare False.
Example 8: reusing a value inside one expression
x = 5
print([x := 10, x * 2], "x now", x) # [10, 20] x now 10
Expressions are evaluated left to right, so the second element already sees the new x. This also shows the danger: the walrus silently overwrote an existing variable in the outer scope. Pick fresh, descriptive names.
Scope rules: what leaks and what does not
res2 = [y for x in nums if (y := slow(x)) > 20]
print("leaked y:", y) # leaked y: 81
Normal comprehension variables like x stay private to the comprehension. A walrus target like y deliberately leaks into the surrounding function or module, holding the last assigned value. That is what made examples 6 and 7 work, but it can also surprise you when a name is reused later. The rules in short:
- At module or function level it behaves like normal assignment.
- Inside a comprehension, it binds in the containing scope.
- It cannot rebind the comprehension’s own loop variable.
Precedence: why parentheses matter
print((t := 5 > 3)) # True: t is the result of 5 > 3
print((u := 5) > 3, u) # True 5: u is 5
The walrus has the lowest precedence of all operators except the comma, so t := 5 > 3 stores the comparison result, not 5. If you meant to store the number, wrap the assignment itself in parentheses, as in the second line. This is the most common walrus bug, and it does not raise an error, so wrap the assignment explicitly every time.
Tip: treat the parentheses as part of the syntax. if (n := len(data)) > 3: reads clearly and always does what you expect.
Where the walrus is not allowed
- As a standalone statement without parentheses, as shown above.
- To assign to attributes, subscripts or tuples: only simple names.
- Inside a comprehension in a class body. We got:
SyntaxError: assignment expression within a comprehension cannot be used in a class body. - To rebind a comprehension iteration variable.
- Unparenthesized as a default value, as in
def f(a=y := 1), which is a syntax error;def f(a=(y := 1))is accepted. Attributes are rejected too:(o.a := 1)gavecannot use assignment expressions with attribute.
Is the walrus operator faster?
Only when it removes repeated work. We compared a regex comprehension that calls search() twice per line with a walrus version that calls it once, over 3,000 lines (best of three runs, 200 loops each):
| Version | Time per run |
|---|---|
[p.search(l).group(1) for l in lines if p.search(l)] |
2.569 ms |
[m.group(1) for l in lines if (m := p.search(l))] |
2.473 ms |
The gain was small here because a third of our lines did not match and regex search is fast. The saving grows with how expensive the repeated call is, as the call counter in example 4 showed. The main benefit is clarity and correctness, not raw speed.
When not to use the walrus operator
- When a normal line is clearer.
n = len(data)followed byif n > 3:is perfectly fine. - Several walruses in one expression. Readers have to track multiple hidden assignments.
- Clever state tricks in comprehensions. Prefer
itertools.accumulateor a plain loop. - Libraries that still support Python 3.7. The code will not parse there.
- Team style guides that forbid it. Consistency beats cleverness. Linters such as Ruff can flag both missed opportunities and misuse.
A good rule of thumb: use it when it removes a duplicated call or a while True plus break, and skip it otherwise. Pair it with type hints so that values captured in conditions stay easy to understand.
Final thoughts
The Python walrus operator is a small feature with a clear job: assign a value and use it in the same expression. It shines in if checks on expensive results, regex matches, read-until-empty loops and comprehensions that would otherwise compute twice. Wrap it in parentheses, remember that it leaks out of comprehensions, and choose a plain assignment whenever that reads better. Used that way, := makes code shorter and clearer at the same time.
Frequently asked questions
What does := mean in Python?
It is the walrus operator, an assignment expression added in Python 3.8. It assigns a value to a name and also returns that value, so it can be used inside conditions, loops and comprehensions.
Which Python version supports the walrus operator?
Python 3.8 and later. Code that uses it raises a syntax error on Python 3.7 and earlier, so avoid it in libraries that must support those versions.
Why does my walrus assignment store True instead of the number?
The walrus has very low precedence, so in t := 5 > 3 the comparison runs first. Wrap the assignment in its own parentheses, as in (t := 5) > 3, to store the number.
Does the walrus variable leak out of a list comprehension?
Yes. A name assigned with the walrus inside a comprehension is bound in the enclosing scope and keeps the last value, unlike the normal loop variable, which stays private.
Is the walrus operator faster than normal assignment?
Not by itself. It only saves time when it removes a repeated function call, such as computing a value once in a comprehension filter instead of twice.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.