Introduced in Python 3.10, match compares a value against a series of patterns. It's more than a switch statement — it can look inside data (lists, tuples, objects) and pull values out while it matches, which is where it really shines.
Matching values
The simplest form matches literal values — a clean alternative to a long if/elif chain:
def http_status(code):match code:case 200:return "OK"case 404:return "Not Found"case 500:return "Server Error"case _: # wildcard — matches anything (the default)return "Unknown"
Destructuring patterns
Patterns can match the shape of data and bind parts of it to names in one step:
def describe(command):match command.split():case ["go", direction]: # a 2-item list; bind the 2ndreturn f"Moving {direction}"case ["drop", *items]: # 'drop' then any number of itemsreturn f"Dropping {items}"case ["quit"]:return "Goodbye"case _:return "Unknown command"describe("go north") # 'Moving north'describe("drop key map") # "Dropping ['key', 'map']"
Guards
Add an if guard to a case for extra conditions beyond the shape:
match point:case (x, y) if x == y:print("on the diagonal")case (x, y):print(f"at ({x}, {y})")
Key takeaways
- 01match/case compares a value against structural patterns (Python 3.10+).
- 02case _ is the wildcard catch-all (the default branch).
- 03Patterns can destructure lists, tuples and objects, binding parts to names.
- 04Add an if guard to a case for extra conditions.
- 05For simple value checks, if/elif remains perfectly fine.
