Q1What does the following code print?items = [10, 20, 30]
if (n := len(items)) >= 2:
print(n)
The Walrus Operator := for Assigning and Testing in One Line
Use Python 3.8's walrus operator := to assign and test in one line, with every example runnable in your browser.
The walrus operator := was introduced in Python 3.8 to let you assign and test in one line. The := shape looks like walrus tusks — hence the name. It cuts down on boilerplate when the same value is reused inside an if or while condition.
The basics of the walrus operator
The regular = is a statement and can't appear inside expressions — so you can't put it in the condition of if or while. := is an expression, so it can go directly inside a condition.
With variable := expression, you assign the result to the variable and use that same value as the condition's value.
The left column (normal) writes assignment and test on separate lines. The right column (walrus) assigns and tests in a single condition.
# Normal style (two lines)
cart = ["apple", "bread", "milk", "eggs"]
n = len(cart)
if n >= 3:
print(f"{n} items: free shipping")
# Walrus version (one line: assign + test)
if (n := len(cart)) >= 3:
print(f"{n} items: free shipping")
# Output: 4 items: free shipping
Wrap it in parentheses inside a condition
if n := len(cart) >= 3: without parentheses evaluates len(cart) >= 3 first and assigns True/False to n. The idiom is (n := len(cart)) >= 3 — wrap the assignment in parentheses.
Using the walrus operator with if
A common pattern in if is needing the tested value inside the body too. Normally you split "assign, then test" across two lines, but the walrus operator lets you write it once, right where the value is needed.
# Branch on the number of search results, then use it in the body
search_results = ["Book A", "Book B", "Book C", "Book D", "Book E"]
if (hit_count := len(search_results)) >= 3:
print(f"{hit_count} results found")
else:
print("Too few results")
# Output: 5 results found
Using the walrus operator with while
In while, the walrus shines when you want the pulled-out value to serve as both the condition and something you use inside the body.
Each iteration checks whether the queue is empty first. If it is, short-circuit evaluation skips pop() and exits the loop. Otherwise queue.pop(0) takes the head and assigns it to task, and the body runs with task before looping again.
# Drain a queue one item at a time from the head
pending_jobs = ["send email", "backup", "deploy"]
while pending_jobs and (job := pending_jobs.pop(0)):
print(f"processing: {job}")
# processing: send email / processing: backup / processing: deploy
# As soon as pending_jobs becomes empty, the left side evaluates False and pop() is skipped — the loop exits.
pending_jobs and (job := pending_jobs.pop(0)) exits the loop via short-circuit evaluation the instant the left side is empty (False). That avoids the bug of calling pop() on an empty list and triggering IndexError.
When to use it and when not to
The walrus operator adds no capability beyond saving keystrokes. Writing logic in one line is convenient, but it can also hurt readability, so be selective about when to reach for it.
| Situation | Recommendation | Why |
|---|---|---|
| Reusing the tested value inside the body | Use it | Splitting across two lines puts the variable far from where it's used |
| In while, using the popped value as both the condition and inside the body | Use it | Combines the loop's exit condition with the take-out |
| Complex computation or side effects inside the condition | Avoid | Hiding work inside an expression makes flow hard to follow |
| Just a plain assignment with no condition | Don't use it | Plain `=` is simpler and easier to read |
In this article you learned how to use the walrus operator := to combine assignment and testing into a single expression.
Knowledge Check
Answer each question one by one.
Q2Which is the correct way to use the walrus operator inside an if condition?
Q3Which statement best describes the walrus operator :=?