matchIntermediate Examples

Begins a structural pattern matching block (3.10+)

Destructuring patterns

Matching and extracting data from structures.

python
# Sequence patterns
point = (3, 4)
match point:
    case (0, 0):
        print("Origin")
    case (x, 0):
        print(f"On x-axis at {x}")
    case (0, y):
        print(f"On y-axis at {y}")
    case (x, y):
        print(f"Point at ({x}, {y})")

# Mapping patterns
config = {"type": "circle", "radius": 5}
match config:
    case {"type": "circle", "radius": r}:
        print(f"Circle with radius {r}, area = {3.14 * r**2:.1f}")
    case {"type": "rectangle", "width": w, "height": h}:
        print(f"Rectangle {w}x{h}, area = {w*h}")

# Nested patterns
data = {"user": {"name": "Alice", "role": "admin"}}
match data:
    case {"user": {"name": str(name), "role": "admin"}}:
        print(f"Admin: {name}")
    case {"user": {"name": str(name)}}:
        print(f"User: {name}")
Expected Output
Point at (3, 4)
Circle with radius 5, area = 78.5
Admin: Alice

match can destructure sequences, mappings, and nested structures. Capture variables extract values from the matched structure.

Guard clauses in match

Adding conditions to case patterns.

python
# Guards with 'if'
def classify(value):
    match value:
        case int(n) if n < 0:
            return "negative integer"
        case int(n) if n == 0:
            return "zero"
        case int(n) if n > 0:
            return "positive integer"
        case float(f) if f != f:  # NaN check
            return "NaN"
        case float(f):
            return f"float: {f}"
        case str(s) if len(s) == 0:
            return "empty string"
        case str(s):
            return f"string: {s!r}"
        case _:
            return f"other: {type(value).__name__}"

for v in [-5, 0, 42, 3.14, float("nan"), "", "hello", [1]]:
    print(f"  {v!r:>10} -> {classify(v)}")

Guards (if clauses) add conditions to case patterns. The pattern must match AND the guard must be True for the case to execute.

Want to try these examples interactively?

Open Intermediate Playground