Skip to main content
Albero Academy

match / case

Structural pattern matching — a powerful switch introduced in Python 3.10.

Flow Control10 min

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:

literal patterns
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:

matching structure
def describe(command):
match command.split():
case ["go", direction]: # a 2-item list; bind the 2nd
return f"Moving {direction}"
case ["drop", *items]: # 'drop' then any number of items
return 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:

a pattern with a guard
match point:
case (x, y) if x == y:
print("on the diagonal")
case (x, y):
print(f"at ({x}, {y})")

Key takeaways

  1. 01match/case compares a value against structural patterns (Python 3.10+).
  2. 02case _ is the wildcard catch-all (the default branch).
  3. 03Patterns can destructure lists, tuples and objects, binding parts to names.
  4. 04Add an if guard to a case for extra conditions.
  5. 05For simple value checks, if/elif remains perfectly fine.

Finished this chapter?

Mark it complete to track your progress through Python.