match Statement

Structural pattern matching — compare a value's shape against a series of patterns and run the first one that fits.

                match subject:
    case pattern:
        ...

              

Purpose

match compares a subject value against a sequence of case patterns, top to bottom, and runs the body of the first one that matches. A bare case _: matches anything and conventionally goes last, as a catch-all.

Example

def describe_status(code: int) -> str:
    match code:
        case 200:
            return "OK"
        case 404:
            return "Not Found"
        case 500:
            return "Server Error"
        case _:
            return "Unknown"

Behavior notes

  • Patterns can do more than match literal values: case [x, y] destructures a two-element sequence, case {"status": code} matches a mapping with that key, and case int() | float(): matches by type. This entry covers only literal-value matching, which is the form most beginner code needs — the richer pattern forms are worth exploring once this one feels comfortable, via the official match statement documentation.
  • case _: is a wildcard, not a variable capture in the usual sense — it matches anything and binds nothing.
  • Unlike a chain of if/elif, match can destructure its subject as part of matching, not just compare it — that’s the actual feature if/elif can’t replicate.

Common mistakes

  • Reaching for match as a drop-in replacement for a simple if/elif chain comparing one variable to a handful of literals — either works for that case, and if/elif is often more familiar to a reader seeing it for the first time. match earns its place once the patterns genuinely destructure structure, not just compare literals.
  • Forgetting the wildcard case (case _:) and assuming an unmatched value silently does nothing — it does, actually: a match statement with no matching case and no wildcard simply falls through with no error, which can hide a genuine bug.

Implementation notes

match is a language feature — but a real, version-gated one: unavailable before Python 3.10. Any codebase or example that needs to support earlier versions has to use an if/elif chain instead.

Taught in these lessons