Learn by reading through in order

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.

Normal assignment vs. the walrus operator
n = len(cart)if (n := len(cart))if n >= 3:evaluate >= 3run the bodyrun the bodyTrueassign + readTrue

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

Use the walrus operator to check a shopping cart total.

① Define cart_prices = [1200, 800, 3500, 600] (the price of each item).

② Inside the if condition, write (total := sum(cart_prices)) >= 5000. When the total is 5000 or more, print "{total} yen: free shipping"; otherwise print "{total} yen: {5000 - total} yen more for free shipping".

③ After the if block, call print(total) to confirm the same total is still accessible outside.

(The explanation appears once the code runs correctly.)

Python Editor

Run code to see output

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.

while queue and (task := queue.pop(0))
while loop startsqueue empty?task := queue.pop(0)exit loop(done)use task in bodynext iterationnot emptyempty (False)got a task

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.

Print a list of search candidates one at a time from the top.

① Define candidates = ["Alice Smith", "Bob Johnson", "Carol Williams"].

② Use while candidates and (name := candidates.pop(0)): to pop one off the front and print "Candidate: {name}".

③ After the loop, print "All candidates checked".

Python Editor

Run code to see output

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.

SituationRecommendationWhy
Reusing the tested value inside the bodyUse itSplitting 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 bodyUse itCombines the loop's exit condition with the take-out
Complex computation or side effects inside the conditionAvoidHiding work inside an expression makes flow hard to follow
Just a plain assignment with no conditionDon't use itPlain `=` 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.

QUIZ

Knowledge Check

Answer each question one by one.

Q1What does the following code print?
items = [10, 20, 30]
if (n := len(items)) >= 2:
print(n)

Q2Which is the correct way to use the walrus operator inside an if condition?

Q3Which statement best describes the walrus operator :=?