1. Home
  2. Blog
  3. Software Development

Software Development

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.

9 min read
Python walrus operator explained with 8 real examples

Key takeaways

  • 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 := 1 and items[0] := 1 are not allowed.
  • A bare walrus as a whole statement is rejected: y := 5 raised SyntaxError: 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) gave cannot 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 by if n > 3: is perfectly fine.
  • Several walruses in one expression. Readers have to track multiple hidden assignments.
  • Clever state tricks in comprehensions. Prefer itertools.accumulate or 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

Work with Stack Quora

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.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

K Nearest Neighbors (KNN) Explained: How It Works, With Python Code

K nearest neighbors explained: the KNN algorithm, a from-scratch NumPy version, choosing k, feature scaling, distance metrics, regression and vector…

Read article →
Software Development

HTTP Cookies Explained: Secure, HttpOnly, SameSite and Scope

HTTP cookies explained: Set-Cookie, Path, Domain, expiry, Secure, HttpOnly, SameSite, prefixes, deleting cookies and a secure session recipe, tested locally.

Read article →
DevOps

Git Rebase Interactive: Squash, Fixup, Reword and Autosquash

Git rebase interactive explained step by step: pick, reword, squash, fixup, edit, drop, autosquash, conflicts and undoing a rebase with…

Read article →
Software Testing

Alpha vs Beta Testing: Key Differences, Exit Criteria and Checklist

Alpha vs beta testing compared: who tests, what each phase finds, entry and exit criteria, how to run a beta,…

Read article →
Test Automation

Pytest Monkeypatch: 10 Tested Examples for Env Vars, Time and APIs

Pytest monkeypatch explained with 10 passing tests: environment variables, functions, config, time, sleeps, paths, blocking the network and the wrong-target…

Read article →
Databases & SQL

SQL Auto Increment: MySQL, PostgreSQL, SQL Server and SQLite

SQL auto increment in MySQL, PostgreSQL, SQL Server and SQLite: syntax, reading the new ID, why gaps appear, ID reuse,…

Read article →
Databases & SQL

SQL BETWEEN: Inclusive Ranges and the Date Trap Explained

SQL BETWEEN explained with tested queries: inclusive ranges, reversed bounds, NULLs, the last-day date trap, half-open ranges and index-friendly date…

Read article →
Software Development

JavaScript Template Literals: 10 Examples Including Tagged Templates

JavaScript template literals explained with 10 tested examples: interpolation, multiline strings, escaping, tagged templates for safe HTML and SQL, and…

Read article →
Software Development

Python heapq: Priority Queues, Top N and Heaps Explained

Python heapq explained: heappush, heappop, heapify, priority queues with tie-breakers, max heaps, nlargest and merge, with real timings against sorting.

Read article →
Software Development

Python Walrus Operator (:=) Explained With 8 Real Examples

The Python walrus operator := explained with 8 tested examples: if checks, regex matches, while loops, comprehensions, scope rules, precedence…

Read article →
Artificial Intelligence

Softmax Function Explained: Formula, Python Code and Stable Version

The softmax function explained: formula, worked example, NumPy code, the stable version that avoids NaN, temperature, cross-entropy and softmax vs…

Read article →
Software Development

CORS Explained: Preflight Requests, Headers and How to Fix CORS Errors

CORS explained: origins, simple and preflight requests, the response headers your server must send, credentials, and how to fix common…

Read article →
DevOps

Git Diff Explained: Staged Changes, Branches and Commits

Git diff explained: read the output, compare unstaged and staged changes, commits and branches, two dots vs three dots, and…

Read article →
Test Automation

Pytest Xdist: Run Tests in Parallel and Cut Test Time

Run pytest tests in parallel with pytest-xdist: install, the -n option, distribution modes, real timings and how to fix shared-state…

Read article →
Software Testing

Verification vs Validation in Software Testing: Example and Table

Verification vs validation in software testing explained with a comparison table and a tested coupon example where every spec test…

Read article →
Databases & SQL

SQL CAST Explained: Convert Data Types With Tested Examples

SQL CAST explained with tested examples: text to number, truncation, integer division, numbers stored as text, dates, bad input and…

Read article →
Databases & SQL

SQL DISTINCT: How to Remove Duplicate Rows (and Its Traps)

SQL DISTINCT explained with tested queries: one and many columns, NULLs, COUNT DISTINCT, DISTINCT vs GROUP BY, the SUM DISTINCT…

Read article →
Software Development

JavaScript Reduce Explained: 12 Practical Examples

JavaScript reduce explained step by step with 12 practical examples: sums, tallies, grouping, Maps, pipelines, sequential promises and the empty…

Read article →
Artificial Intelligence

Levenshtein Distance: Formula, Worked Table and Python Code

Levenshtein distance explained: the edit operations, the dynamic programming table for kitten and sitting, Python code with two-row memory, normalised…

Read article →
DevOps

Gitignore: Patterns, Negation and Fixing Tracked Files

A tested gitignore guide: pattern rules, leading and trailing slashes, negation with !, the ignored parent folder trap, git check-ignore…

Read article →
Software Testing

Acceptance Criteria: Given When Then Examples and Checklist

How to write acceptance criteria testers can run: rule-based and Given When Then formats, a worked discount code example turned…

Read article →
Software Testing

State Transition Testing: Diagram, Table and Example

State transition testing explained with a login lockout example: states, events, the diagram, the state table, valid and invalid transitions,…

Read article →
Databases & SQL

Second Highest Salary in SQL: 5 Tested Ways and the Tie Trap

Find the second highest salary in SQL five ways: MAX subquery, LIMIT OFFSET, DENSE_RANK, a correlated subquery and per department,…

Read article →
Databases & SQL

SQL ROW_NUMBER: Top N per Group, Dedupe and Pagination

SQL ROW_NUMBER explained with tested queries: PARTITION BY, top N per group, deleting duplicates, pagination, the tie trap and how…

Read article →
Test Automation

Python Unittest: Assert Methods, setUp and Mocks With Examples

A practical Python unittest tutorial: TestCase, assert methods, setUp and tearDown, subTest, skips, expected failures and mock, with a test…

Read article →
Artificial Intelligence

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →