Match statements
Overview
When a value can take many forms and you want different behaviour for each, a long if/elif chain gets repetitive. Python’s match statement (since Python 3.10) compares a value against patterns — exact values, alternatives, and even the shape of a list — and pulls out the parts you need.
Matching values
status = 404
match status:
case 200:
message = "OK"
case 301 | 302:
message = "Redirect"
case 404:
message = "Not found"
case _:
message = "Something else"
print(message) # Not foundmatchtakes a value; eachcaseholds a pattern.- Cases are checked top to bottom; the first match runs and the rest are skipped.
|means “or”:301 | 302matches either.case _:matches anything — the default, likeelse. Put it last.
For simple value checks like this, match reads a little cleaner than if status == 200: … elif status in (301, 302): …. Its real power is with structured data.
Matching the shape of a sequence
command = "go north"
match command.split(): # ["go", "north"]
case ["look"]:
print("You look around.")
case ["go", direction]:
print(f"You walk {direction}.")
case ["take", *items]:
print("You take", items)
case _:
print("Unknown command")A sequence pattern like ["go", direction] matches a list of exactly two items whose first item is "go". The plain name direction is a capture: it matches anything, and that item is stored in the variable. So "go north" runs the second case with direction = "north".
["look"]— exactly one item,"look".["go", direction]— exactly two items, the first"go".["take", *items]—"take"followed by any number of items (even zero), collected in a list.
Capturing with alternatives: as
To restrict a captured value, combine alternatives and name the result with as:
case ["go", ("north" | "south" | "east" | "west") as direction]:
print(f"You walk {direction}.")
case ["go", *other]:
print("You can't go that way.")Order matters again: the specific case comes first, the general fallback second.
Guards
Add if after a pattern for an extra condition:
match point:
case [0, 0]:
print("Origin")
case [x, 0]:
print(f"On the x-axis at {x}")
case [x, y] if x == y:
print("On the diagonal")
case [x, y]:
print(f"At {x}, {y}")If the guard is false, matching continues with the next case.
Matching dictionaries
Patterns can also check dictionary keys — useful for data from JSON or web APIs:
event = {"type": "click", "x": 10, "y": 20}
match event:
case {"type": "click", "x": x, "y": y}:
print(f"Click at {x}, {y}")
case {"type": "key", "key": key}:
print(f"Key pressed: {key}")A mapping pattern matches if the listed keys exist (extra keys are allowed).
A common mistake: names capture, they don’t compare
QUIT = "quit"
match command:
case QUIT: # captures ANY value into a new name called QUIT!
...A bare name in a pattern is always a capture, so this case matches everything (Python even raises an error if more cases follow it). To compare against a constant, use a dotted name — like Command.QUIT from an enum — or a literal value.
match or if?
- Use
matchwhen you’re checking one value against many possibilities, especially the structure of lists, tuples or dictionaries. - Use
if/eliffor a few conditions, ranges (score >= 90), or conditions that involve different variables.
The key idea: a pattern describes what the data looks like, and names in the pattern pull out the parts you need.
A text adventure command parser
Write a function-free command parser for a tiny text adventure. Read one command from the user, split it into words, lower-case it, and use match to respond: look → You see a dusty room.; go north/go south/go east/go west → You walk <direction>.; go on its own → Go where?; go followed by anything else → You can't go <that>.; take followed by one or more items → You take: key, map (joined with commas); quit or exit → Goodbye!; and anything else → I don't understand.
command = input("> ").strip().lower()
match command.split():
# your cases here
case _:
print("I don't understand.")command = input("> ").strip().lower()
match command.split():
case ["look"]:
print("You see a dusty room.")
case ["go", ("north" | "south" | "east" | "west") as direction]:
print(f"You walk {direction}.")
case ["go"]:
print("Go where?")
case ["go", *other]:
print(f"You can't go {' '.join(other)}.")
case ["take", first, *rest]:
print("You take:", ", ".join([first, *rest]))
case ["quit"] | ["exit"]:
print("Goodbye!")
case _:
print("I don't understand.")Summary
match value:checkscasepatterns from top to bottom and runs the first one that matches.- Literal patterns match exact values;
|combines alternatives;case _:matches anything. - Sequence patterns like
["go", direction]check the shape and capture parts into names. *restcaptures any number of remaining items;ifguards add extra conditions.- Use match for many-way choices on the shape of data; a simple if/elif is still fine for a few conditions.