# Walrus Operator and Structural Pattern Matching

> What is the walrus operator (:=) in Python? What is structural pattern matching (match-case)?

Canonical: https://www.internhack.in/learn/interview/python-interview/python-walrus-operator
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

What is the walrus operator (:=) in Python? What is structural pattern matching (match-case)?

## Answer

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.

## Code examples

### Walrus Operator

```
# 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.

### Structural Pattern Matching (match-case)

```
# 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.

## Key points

- Walrus operator has lower precedence than most operators - use parentheses in complex expressions
- match-case is not a hash-table lookup like C switch - it uses pattern matching
- Patterns can match class instances: case Point(x=0, y=0)
- match-case does not fall through by default (unlike C switch)

## Common follow-up questions

- What are the precedence rules for the walrus operator?
- How does match-case differ from a series of if/elif statements?
- Can you use match-case with custom classes?

## Interview tips

- The walrus operator in while loops (reading input) is the clearest use case
- match-case shows awareness of modern Python - many interviewers are still learning it
- Guards in match-case (if ...) are a powerful feature worth demonstrating

## Concepts covered

Walrus Operator, :=, match-case, Structural Pattern Matching, Python 3.10

Previous: [@property and Descriptors](https://www.internhack.in/learn/interview/python-interview/python-property-descriptor) · Next: [Protocol and Structural Subtyping](https://www.internhack.in/learn/interview/python-interview/python-protocols) · [All of Python Interview](https://www.internhack.in/learn/interview/python-interview)

## More Python Interview questions

- [concurrent.futures and Multiprocessing](https://www.internhack.in/learn/interview/python-interview/python-concurrent-futures)
- [Closures, LEGB Rule, and nonlocal](https://www.internhack.in/learn/interview/python-interview/python-closures-scope)
- [classmethod vs staticmethod](https://www.internhack.in/learn/interview/python-interview/python-classmethod-staticmethod)
- [Enum in Python](https://www.internhack.in/learn/interview/python-interview/python-enum)
- [pathlib and File System Operations](https://www.internhack.in/learn/interview/python-interview/python-pathlib)
- [Python Logging Module](https://www.internhack.in/learn/interview/python-interview/python-logging)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Python Interview](https://www.internhack.in/learn/interview/python-interview)
