Table of Contents

Python walrus operator

Python walrus operator (:=) is assignment expression syntax that assigns a value and returns it in a single expression. It lets you compute a value once, assign it to a variable, and use that variable—all in one expression, reducing duplication and improving readability in loops and conditionals.

Use walrus operator to avoid computing expensive values twice or to assign in conditionals where assignment isn't normally allowed.

Example

This example shows walrus operator reducing duplicate computation.

# run: python3 walrus_operator.py
# description: assignment expressions with :=
 
# Without walrus: compute twice or use extra variable
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 
# Old way: extra variable
filtered = [x for x in data if x > 5]
print(f"Old way: {filtered}")
 
# New way: walrus in conditional
filtered = [x for x in data if (n := len(data)) and x > 5]
print(f"With walrus: {filtered}")
 
# Assignment in while loop
import io
input_stream = io.StringIO("line1\nline2\nline3\n")
 
# Old way: assign, then check
line = input_stream.readline()
while line:
    print(f"Read: {line.strip()}")
    line = input_stream.readline()
 
# New way: walrus operator
input_stream = io.StringIO("line1\nline2\nline3\n")
while (line := input_stream.readline()):
    print(f"Read: {line.strip()}")
 
# Avoid computing expensive value twice
def expensive_computation():
    print("  (expensive...)")
    return 42
 
# Old: compute twice or use temp var
if expensive_computation() > 40:
    result = expensive_computation()
    print(f"Result: {result}")
 
# New: walrus operator
if (result := expensive_computation()) > 40:
    print(f"Result: {result}")
 
# List comprehension with condition on computed value
numbers = [10, 20, 30, 40, 50]
filtered = [y for x in numbers if (y := x * 2) > 50]
print(f"Filtered: {filtered}")

Common patterns

In conditionals:

In while loops:

In list comprehensions:

Variable scope:

Readability trade-off:

Introduced in Python 3.8:

Common misuses to avoid: