Match Case and Pattern Matching
Master structural pattern matching in Python 3.10+ using match and case statements, literal patterns, sequence deconstruction, guards, and wildcard fallbacks.
For decades, developers coming to Python from languages like C, Java, or JavaScript asked the same question: “Where is Python’s switch statement?”
Until Python 3.10, Python deliberately avoided a traditional switch statement. Developers used chains of if-elif-else statements or dictionaries. But in Python 3.10, Python introduced something far more capable than a simple switch statement: Structural Pattern Matching using the match and case keywords.
While a traditional switch statement merely compares a single value against constants (value == 1), Python’s pattern matching inspects both the shape (structure) and the contents of your data, unpacking components and binding them to variables in a single expressive step.
1. The Anatomy of a match Statement
At its simplest, match-case works like an elegant, readable alternative to a cascading if-elif-else ladder.
status_code = 404
match status_code:
case 200:
print("Success: OK")
case 400:
print("Client Error: Bad Request")
case 404:
print("Client Error: Resource Not Found")
case 500:
print("Server Error: Internal Failure")
case _:
# The wildcard underscore matches anything not handled above
print("Unhandled HTTP Status Code")
Output:
Client Error: Resource Not Found
Key Rules of match-case:
- The
matchheader: Evaluates the subject expression once (match status_code:). - Sequential evaluation: Python tests each
casebranch from top to bottom. As soon as the first pattern matches, Python executes that block and immediately exits thematchstatement. - No
breakstatements required: Unlike C, Java, or JavaScript where cases “fall through” unless you explicitly typebreak;, Python never falls through. - The Wildcard (
_): An underscorecase _:acts as a catch-all fallback. It matches any value and is equivalent to the finalelse:branch in anifstatement.
2. Combining Patterns with the Pipe (|)
If multiple values should trigger the exact same logic, combine them using the vertical pipe character (|), which acts as an OR operator:
weekday = "Saturday"
match weekday:
case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":
print("It is a working weekday. Time to code!")
case "Saturday" | "Sunday":
print("It is the weekend! Time to recharge.")
case _:
print("Not a valid day name.")
Output:
It is the weekend! Time to recharge.
3. Structural Deconstruction: Unpacking Sequences
The true power of structural pattern matching becomes apparent when working with complex data structures like lists and tuples. Python can inspect the length of a sequence and unpack its elements into named variables simultaneously.
Imagine writing a text parser for a terminal game or command-line utility:
def process_command(command):
match command:
# Matches a list with exactly one item: "quit"
case ["quit"]:
print("Shutting down the game engine...")
# Matches a 2-item list starting with "look"
case ["look", target]:
print(f"You inspect the {target} closely.")
# Matches a 3-item list starting with "transfer"
case ["transfer", amount, recipient]:
print(f"Transferring ${amount} to account '{recipient}'...")
# Matches any list starting with "broadcast", gathering everything else into a list
case ["broadcast", *messages]:
print(f"Broadcasting to everyone: {' '.join(messages)}")
case _:
print(f"Error: Unknown command sequence {command}")
# Test different shapes and commands:
process_command(["look", "treasure chest"])
process_command(["transfer", 250, "Alice"])
process_command(["broadcast", "Server", "maintenance", "in", "5m"])
process_command(["quit"])
Output:
You inspect the treasure chest closely.
Transferring $250 to account 'Alice'...
Broadcasting to everyone: Server maintenance in 5m
Shutting down the game engine...
Notice what happened in case ["look", target]:! Python verified that:
commandis a sequence.commandcontains exactly two elements.- The first element is the literal string
"look". - If all three criteria matched, Python automatically extracted the second item and assigned it to the brand new variable
target!
4. Pattern Guards: Adding if Conditions
Sometimes matching the shape is not enough; you also need to validate a dynamic condition on the unpacked values. You can attach a guard condition to any case using the if keyword:
coordinates = (15, -4)
match coordinates:
case (0, 0):
print("Point is at the exact origin.")
case (x, 0):
print(f"Point lies on the X-axis at {x}")
case (0, y):
print(f"Point lies on the Y-axis at {y}")
case (x, y) if x > 0 and y > 0:
print(f"Point ({x}, {y}) is in Quadrant I (top-right)")
case (x, y) if x < 0 and y > 0:
print(f"Point ({x}, {y}) is in Quadrant II (top-left)")
case (x, y) if x < 0 and y < 0:
print(f"Point ({x}, {y}) is in Quadrant III (bottom-left)")
case (x, y) if x > 0 and y < 0:
print(f"Point ({x}, {y}) is in Quadrant IV (bottom-right)")
case _:
print("Invalid coordinate format.")
Output:
Point (15, -4) is in Quadrant IV (bottom-right)
[!NOTE] Python only tests the guard (
if x > 0 and y < 0) after the structural match(x, y)succeeds. If the guard evaluates toFalse, Python does not abort; it simply moves on to test the nextcasebranch.
5. Capturing Patterns with as
If you want to match a sub-pattern while still keeping a reference to the whole structure, use the as keyword:
event = ["click", (120, 480)]
match event:
case ["click", (int(x), int(y)) as point]:
print(f"Mouse clicked at coordinates {point}: X={x}, Y={y}")
case _:
print("Unsupported event")
Here, point receives the tuple (120, 480), while x and y receive 120 and 480 respectively.
6. Common Traps & Gotchas
Trap 1: Variable Names Are Capture Patterns, NOT Equality Checks!
This is the number one mistake beginners make when using match-case:
# Intended: Check if response equals the constant EXPECTED_CODE
EXPECTED_CODE = 200
response = 404
match response:
case EXPECTED_CODE: # WARNING: This does NOT compare response == EXPECTED_CODE!
print("Matched expected code!")
Why does this print "Matched expected code!" even though response is 404?
In Python pattern matching, a plain variable name like EXPECTED_CODE inside a case statement is treated as a capture variable. It rebinds the variable EXPECTED_CODE to the value of response (404) and matches unconditionally!
The Fix: To match against external constants or enumeration values, use dotted names or a guard:
import http
response = 404
match response:
# Dotted names are treated as equality lookups, not variable bindings
case http.HTTPStatus.OK:
print("Success 200")
case _ if response == EXPECTED_CODE:
print("Matched custom constant")
case _:
print("Different response code")
Trap 2: Catch-All case _ Must Be Last
Because case _: matches literally every value, placing it anywhere before other case statements will cause Python to raise a SyntaxError: wildcard makes remaining patterns unreachable.
7. match-case vs if-elif-else: When to Use Which?
| Feature / Goal | if-elif-else | match-case |
|---|---|---|
Simple range checks (e.g. score >= 80) | Ideal and concise | Clunky; requires awkward guards |
Boolean flags (e.g. if is_admin:) | Best practice | Overkill |
| Parsing command inputs & sequences | Verbose (len(cmd) == 2 and cmd[0] == ...) | Beautiful, declarative unpacking |
| Matching structured payloads (APIs, ASTs) | Nested and error-prone | Clean, self-documenting |
| Python Version Support | All Python versions (Python 1.0+) | Requires Python 3.10+ |
Summary & Practice
- Structural pattern matching with
match ... casedeconstructs data shapes and values simultaneously. - Wildcard
case _:serves as the default fallback branch. - Combine values with
|(OR) and constrain patterns usingifguards. - Never use a bare identifier expecting an equality check; bare identifiers bind variables.
Next, master how to repeat execution automatically across sequences and conditions in loops.