Match statements

Topic 3 of 3 in Making decisions6 min readBeginnerFree course

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

Python
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 found
  • match takes a value; each case holds a pattern.
  • Cases are checked top to bottom; the first match runs and the rest are skipped.
  • | means “or”: 301 | 302 matches either.
  • case _: matches anything — the default, like else. 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

match: compare a value against patterns. The code matches command.split(): case [“quit”] calls stop(); case [“go”, direction] calls move(direction); case [“take”, *items] calls pick_up(items); and case _ prints Unknown command. Inputs and what they match: “quit” matches the first case; “go north” sets direction = “north”; “take key map” sets items = [“key”, “map”]; “dance” falls through to case _ (anything).

Python
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:

Python
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:

Python
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:

Python
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

Python
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 match when you’re checking one value against many possibilities, especially the structure of lists, tuples or dictionaries.
  • Use if/elif for 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.

Exercise

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.

Python
command = input("> ").strip().lower()

match command.split():
    # your cases here
    case _:
        print("I don't understand.")

Summary

  • match value: checks case patterns 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.
  • *rest captures any number of remaining items; if guards 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.