Difficulty: Intermediate
What is the walrus operator (:=) in Python? What is structural pattern matching (match-case)?
Walrus operator (:=) - also called assignment expression (Python 3.8+): assigns a value as part of an expression. Useful for reusing a computed value in the same expression.
Common use cases: while loops reading input, avoiding double-calling functions, list comprehension filters.
Structural pattern matching (match-case, Python 3.10+): like switch-case but with powerful pattern deconstruction for sequences, mappings, classes, and guards.
# Without walrus: compute twice or use temp var
data = [1, 2, 3, 4, 5]
result1 = [y for x in data if (y := x2) > 10]
print(result1) # [16, 25] - y is computed once per element
# Reading until EOF
import io
stream = io.StringIO('line1\nline2\nline3')
while chunk := stream.readline():
print(chunk.strip())
# Re-using regex match
import re
text = 'Error: File not found (code: 404)'
if m := re.search(r'code: (\d+)', text):
print(f'Error code: {m.group(1)}')
# Avoiding redundant computation
def expensive():
print('computed')
return [1, 2, 3]
# Without walrus: expensive() called twice
if expensive(): # call 1
print(len(expensive())) # call 2
# With walrus: called once
if result := expensive():
print(len(result))
The walrus operator assigns and evaluates in one step. In the list comprehension, y = x2 is computed once but used in both the filter and the result.
# Python 3.10+
def handle_command(command):
match command.split():
case ['quit']:
return 'Quitting'
case ['go', direction] if direction in ('north', 'south'):
return f'Going {direction}'
case ['go', direction]:
return f"Can't go {direction}"
case ['get', item, *rest]:
return f'Getting {item} from {rest}'
case _:
return 'Unknown command'
print(handle_command('quit')) # Quitting
print(handle_command('go north')) # Going north
print(handle_command('get sword room')) # Getting sword from ['room']
# Matching data structures
def describe(point):
match point:
case {'x': 0, 'y': 0}:
return 'Origin'
case {'x': x, 'y': 0}:
return f'X-axis at {x}'
case {'x': 0, 'y': y}:
return f'Y-axis at {y}'
case {'x': x, 'y': y}:
return f'Point at ({x}, {y})'
print(describe({'x': 0, 'y': 0})) # Origin
print(describe({'x': 3, 'y': 0})) # X-axis at 3
print(describe({'x': 1, 'y': 2})) # Point at (1, 2)
match-case deconstructs sequences and mappings. Guards (if ...) add conditions. *rest captures remaining items. case _ is the default.
Walrus Operator, :=, match-case, Structural Pattern Matching, Python 3.10