Skip to content

Walrus Operator (:=)

The walrus operator (:=) allows assignment within expressions, introduced in Python 3.8 (2019). It assigns values while using them in the same expression.

Had to assign before using:

# Assign then use
line = input("Enter: ")
if line:
print(f"You entered: {line}")
# Repeat expression
data = get_data()
if data:
process(data)
# Loop requires extra variable
match = re.search(pattern, text)
while match:
handle(match)
match = re.search(pattern, text)

Assign and use in one expression:

# Inline assignment in if
if (line := input("Enter: ")):
print(f"You entered: {line}")
# Avoid repeating function call
if (data := get_data()):
process(data)
# Cleaner loops
while (match := re.search(pattern, text)):
handle(match)
text = text[match.end():]
# List comprehension with intermediate value
values = [1, 2, 3, 4, 5]
squares = [(x, y) for x in values if (y := x ** 2) > 10]
# [(4, 16), (5, 25)]
# Avoid redundant computation
data = [10, 20, 30, 40]
if (n := len(data)) > 5:
print(f"Large dataset: {n} items")
else:
print(f"Small dataset: {n} items")
# Read file in chunks
with open('file.txt', 'rb') as f:
while (chunk := f.read(1024)):
process(chunk)
# Parse and validate
import re
if (match := re.match(r'(\d+)-(\d+)', "123-456")):
start, end = match.groups()
print(f"Range: {start} to {end}")
  • Concise: Combines assignment and use
  • DRY: Avoid repeating expressions
  • Readable: Intent is clear (when not overused)
  • Efficient: Compute once, use multiple times
  • Scoping: Variable available in scope
  • Parentheses required in most contexts
  • Variable scope follows normal rules
  • Canโ€™t use in lambda (without parentheses around entire lambda)
  • Donโ€™t overuse (readability matters)
  • Not the same as == (assignment, not comparison)
# Parentheses required
# if x := 5: # SyntaxError
if (x := 5): # OK
print(x)
# Scope
if (x := 10):
print(x) # 10
print(x) # 10 - still in scope
# List comprehension scope
[x for x in range(10) if (y := x * 2) > 5]
# y is NOT accessible here (comprehension scope)
# Don't confuse with ==
if (x := 5): # Assignment
print("x is assigned")
if x == 5: # Comparison
print("x equals 5")
# Bad: too complex
# DON'T DO THIS
if (data := get_data()) and (processed := process(data)) and (valid := validate(processed)):
save(valid)
# Better: multiple statements
  1. Rewrite using walrus: n = len(items); if n > 0: print(n)

    Answer
    if (n := len(items)) > 0:
    print(n)
  2. Use walrus to read lines from a file until empty line

    Answer
    while (line := input()):
    print(line)
  3. When should you avoid the walrus operator?

    Answer When it reduces readability, creates overly complex expressions, or when simple separate statements are clearer.