Site Tools


python-walrus-operator

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:

  • if (x:= expensive_func()) > threshold:: assign and test in one expression
  • Avoids calling function twice or using temporary variable

In while loops:

  • while (line:= file.readline()):: read and test for EOF
  • Standard idiom for reading until end of stream

In list comprehensions:

  • [f(y) for x in data if (y:= transform(x)) > threshold]: reuse computed value
  • Avoids computing transform twice

Variable scope:

  • Walrus operator creates variable in enclosing scope (unlike list comprehension variables)
  • [y for x in range(5) if (y:= x*2)]: y is in outer scope after comprehension

Readability trade-off:

  • Makes code more concise
  • Can make it harder to read if overused
  • Best for: avoiding duplicate computation, loop conditions
  • Avoid: overly nested expressions, reducing clarity

Introduced in Python 3.8:

  • Not available in earlier versions
  • Part of PEP 572
  • Rarely essential; usually alternatives exist (temp variable, refactor function)

Common misuses to avoid:

  • Don't use just to assign: (x:= 5) when x = 5 is clearer
  • Don't nest walrus operators: if (x:= (y:= f())): is confusing
  • Don't use in one-off code where clarity matters more than brevity
python-walrus-operator.md · Last modified: by 127.0.0.1