Control Flow

Advanced Match Patterns

match patterns can destructure sequences, combine alternatives, and add guards.

Structural pattern matching is more than equality checks. Patterns can destructure sequences, match several alternatives, capture the rest of a sequence, and use guards.

Use these forms when the shape of data is the decision. If the decision is only a single boolean condition, ordinary if statements are usually clearer.

The wildcard _ catches everything not matched earlier.

Sequence patterns match by position. A guard after if adds a condition that must also be true.

Source

command = ["move", 2, 3]

match command:
    case ["move", x, y] if x >= 0 and y >= 0:
        print(f"move to {x},{y}")
    case _:
        print("unknown")

Output

move to 2,3
Capture, alternative, guard, and class patterns each name a different way a value can match a case.

An OR pattern accepts several alternatives in one case. A star pattern captures the rest of a sequence.

Source

for command in [["exit"], ["echo", "hello", "python"]]:
    match command:
        case ["quit" | "exit"]:
            print("stop")
        case ["echo", *words]:
            print(" ".join(words))

Output

stop
hello python

The wildcard _ catches values that did not match earlier cases. Here the guard rejects the negative coordinate, so the same match that accepted ["move", 2, 3] falls through to the fallback.

Source

command = ["move", -1, 3]

match command:
    case ["move", x, y] if x >= 0 and y >= 0:
        print(f"move to {x},{y}")
    case _:
        print("unknown")

Output

unknown

Notes

See also

Run the complete example

Example code

Expected output

move to 2,3
stop
hello python
unknown

Execution time appears here after you run the example.