Control Flow
Advanced Match Patterns
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,3An 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 pythonThe 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
unknownNotes
- Use
case _as a wildcard fallback. - Guards refine a pattern after the structure matches.
- OR patterns and star patterns keep shape-based branches compact.
See also
- related: Match Statements
- next depth: Tuples
- next depth: Classes
Run the complete example
Expected output
move to 2,3
stop
hello python
unknown
Execution time appears here after you run the example.