Python match Statement
In this page:
match subject:
case pattern1:
# block 1
case pattern2 | pattern3:
# block 2
case _:
# default
Basic Match-Case
Introduced in Python 3.10, match/case compares one value against a series of patterns and runs the block for the first match — it reads more like a lookup table than an elif ladder, especially once you're checking more than two or three cases.
Example: Basic Match-Case
command = "start"
match command: # compares command against each case pattern
case "start":
print("Starting")
case "stop":
print("Stopping")
Wildcard Fallback (case _)
The underscore _ acts as a catch-all pattern that always matches, functioning exactly like the final else in an if/elif ladder — Python's linter will also warn you if a match block is missing one and could fall through with no match.
Example: Wildcard Fallback (case _)
command = "pause"
match command:
case "start":
print("Starting")
case _: # catch-all pattern, matches anything not matched above
print("Unknown command")
Grouping Cases with |
The | operator inside a case groups multiple values that should trigger the same block, like case "y" | "yes":, avoiding the need for separate, duplicate cases that do identical work.
Example: Grouping Cases with |
answer = "y"
match answer:
case "y" | "yes": # | groups multiple values for the same case
print("Confirmed")
case _:
print("Not confirmed")
Match-Case with Guards
Adding an if clause after a pattern — called a guard — lets a case match only when both the pattern *and* an extra condition hold, such as case n if n > 0:, combining structural matching with an ordinary boolean check.
Example: Match-Case with Guards
n = 5
match n:
case n if n > 0: # guard: pattern matches n, and the if condition must also hold
print("Positive")
case _:
print("Not positive")
Matching Sequences
Beyond simple value matching, match can destructure sequences directly in the pattern — case [x, y]: binds x and y to a two-element list's contents in one line, something an elif ladder can't express nearly as cleanly.
Example: Matching Sequences
point = [3, 4]
match point:
case [x, y]: # destructures the two-element list into x and y
print(x, y)
- Using
matchon Python before 3.10, where it is aSyntaxError. - Writing a bare name as a pattern like
case RED:, which captures any value into a variable instead of comparing with a constant (useColor.REDor a literal). - Forgetting
case _:, so unmatched values silently do nothing, and expecting fall-through like C'sswitch; only one case ever runs.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: