Match Statement
In one line
match/case is Python's pattern matching (3.10+) — like switch/case but with destructuring, type checks, and guards.
In simple words
The match statement (Python 3.10+, PEP 634) is structural pattern matching. It's far more powerful than a simple switch/case:
- Literal matching —
case 1:,case "hello": - Variable binding —
case [x, y]:unpacks and binds x, y - Type matching —
case Point(x, y):matches class instances - Guards —
case [x, y] if x > y:adds conditions - Wildcard —
case _:matches anything (default)
Patterns are checked top-to-bottom; first match wins. The _ wildcard must be last. This replaces long if/elif chains with cleaner, more readable code.
Example
def handle_command(cmd):
match cmd.split():
case ["quit"]:
return "Exiting"
case ["hello", name]:
return f"Hi {name}"
case ["move", x, y]:
return f"Moving to {x}, {y}"
case ["search", *keywords]: # * captures rest
return f"Searching: {keywords}"
case _:
return "Unknown command"
print(handle_command("hello Alice")) # Hi Alice
print(handle_command("move 10 20")) # Moving to 10, 20
print(handle_command("search py js")) # Searching: ['py', 'js']
# Type matching with classes
class Point:
def __init__(self, x, y):
self.x = x; self.y = y
match Point(1, 2):
case Point(x=0, y=0):
print("origin")
case Point(x=x, y=y):
print(f"point at {x},{y}")match/case supports literals, unpacking, wildcards (*), and guards. Far more powerful than switch/case — it's structural pattern matching.
Common confusions
Confused with: if/elif
The difference: match/case does structural pattern matching — it can destructure, bind variables, and match types/shapes, not just compare values. if/elif only evaluates boolean expressions. match is more declarative and powerful for complex data dispatch, but if/elif is simpler for basic conditions.
Related terms
Related Resources
Related Lessons
- Python Syntax
Match statement.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.