Python Docs

Walrus Operator (:=)

The assignment expression operator := lets you assign and use a value in the same expression. It was introduced in Python 3.8 and helps remove repetition, especially in loops, conditions, and comprehensions.

Basic Usage

Common pattern: read or compute a value, stop when it's empty or invalid.

# Read until blank line
while (line := input("Enter: ")):
    print("You typed:", line)

Conditions & Comprehensions

Use walrus when the same value is needed in the condition and inside the body / comprehension.

def cost(x):
    print("compute", x)
    return x * x

vals = [1, 2, 3]

# Compute once, use for both test and result
squares = [y for x in vals if (y := cost(x)) > 2]
print(squares)  # [4, 9]

Regex Example

Typical pattern: test a match and reuse the same Match object if it exists.

import re

text = "ID: 12345"

if (m := re.search(r"ID: (\d+)", text)):
    print(int(m.group(1)))  # 12345

Loops

You can pull items from a list / iterator until a stopping value appears.

items = [10, 20, 0, 30]

while items and (n := items.pop(0)) != 0:
    print("Processing:", n)

Best Practices

  • Use when you'd otherwise repeat the same expression in a condition and inside the block.
  • Great for input loops, regex parsing, and filtering.
  • Avoid deeply nested walrus expressions – they hurt readability.
  • If the line feels confusing, split it into a normal assignment + condition instead.