Python match Statement Explained with Examples

How Python’s match statement works: literal, sequence, mapping and class patterns, guards, wildcards and the mistakes to avoid. With tested examples.

Python’s match statement compares a value against patterns and runs the first one that fits, and unlike a C-style switch it can take apart lists, dictionaries and objects as it matches. It arrived in Python 3.10 as structural pattern matching (PEP 634), with PEP 635 giving the rationale and PEP 636 a tutorial.

The examples below were run on Python 3.10, 3.14 and 3.15 with identical results, except the type-checker example at the end, which needs Python 3.11 or later and was checked with mypy 2.4.1 on 3.14.

Pattern types at a glance

Pattern Example Matches
Literal case 404: An equal value (None, True and False by identity)
Or case 500 | 502 | 503: Any one of the alternatives
Wildcard case _: Anything, binding nothing
Capture case ["go", direction]: Binds the matched part to a name
Value case Color.RED: A dotted name, compared by equality
Sequence case ["drop", *items]: Lists and tuples of a given shape
Mapping case {"type": "key"}: Dictionaries containing those keys
Class case Point(x=0, y=0): An instance of the class with matching attributes
As case "a" | "b" as letter: Any pattern, also binding the whole match

Add if condition after any pattern to make it a guard.

The basics

def http_status(code: int) -> str:
    match code:
        case 200:
            return "OK"
        case 404:
            return "Not Found"
        case 500 | 502 | 503:
            return "Server error"
        case _:
            return "Other"

print([http_status(c) for c in (200, 404, 502, 418)])
# ['OK', 'Not Found', 'Server error', 'Other']

Cases are tried top to bottom and only the first match runs, so there is no fall-through and no break. | combines alternatives, and _ is the wildcard default.

Sequence patterns

def describe(command: list[str]) -> str:
    match command:
        case []:
            return "empty"
        case ["quit"]:
            return "bye"
        case ["go", direction]:
            return f"going {direction}"
        case ["drop", *items]:
            return f"dropping {len(items)} items"
        case _:
            return "unknown"

print(describe(["go", "north"]))        # going north
print(describe(["drop", "a", "b"]))     # dropping 2 items

A pattern like ["go", direction] both checks the shape (two items, the first being "go") and binds direction to the second. *items captures the rest. Strings, bytes and bytearray are deliberately not treated as sequences: case [a, b] does not match the string "ab", although it does match ["a", "b"] and ("a", "b").

Mapping patterns

def handle(event: dict) -> str:
    match event:
        case {"type": "click", "x": x, "y": y}:
            return f"click at {x},{y}"
        case {"type": "key", "key": key}:
            return f"key {key}"
        case _:
            return "ignored"

print(handle({"type": "click", "x": 1, "y": 2, "extra": 9}))   # click at 1,2

A mapping pattern matches when the listed keys are present and ignores extra keys. To capture the extras, add **others: case {"k": 1, **others} against {"k": 1, "a": 2, "b": 3} binds others to {"a": 2, "b": 3}. This suits JSON-shaped data such as API payloads.

Class patterns

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

def where(p: Point) -> str:
    match p:
        case Point(x=0, y=0):
            return "origin"
        case Point(x=0):
            return "on the y axis"
        case Point(x, y) if x == y:
            return "on the diagonal"
        case _:
            return "elsewhere"

Class patterns check the type and then the attributes. Keyword patterns such as Point(x=0) work with any class. Positional patterns such as Point(x, y) need the class to define __match_args__, which @dataclass generates for you (Point.__match_args__ is ('x', 'y')). With a plain class that lacks it, Python raises TypeError: P() accepts 0 positional sub-patterns (2 given). See dataclasses vs Pydantic vs attrs for these classes.

Guards, as and nested patterns

A guard is an if after a pattern. If it is false, matching moves on to the next case:

def f(v):
    match v:
        case (a, b) if a == b:
            return "same"
        case (a, b):
            return "different"

print(f((1, 1)), f((1, 2)))   # same different

Patterns nest, and as binds a sub-pattern to a name:

def g(v):
    match v:
        case [int() as a, str() as b]:
            return f"int {a}, str {b}"
        case {"user": {"name": str(name)}}:
            return f"nested name {name}"
        case "a" | "b" as letter:
            return f"letter {letter}"
        case [first, *_, last]:
            return f"first {first}, last {last}"
        case _:
            return "other"

The mistakes to avoid

  • Bare names capture; they do not compare. case RED: binds whatever it is given to RED. When more cases follow, Python stops you: SyntaxError: name capture 'RED' makes remaining patterns unreachable. Inside a larger pattern it does not stop you. With RED = "red", running case ("paint", RED): against ("paint", "blue") matches and quietly sets RED to "blue". Use a dotted name such as Color.RED, or a literal, to compare.
  • A wildcard must come last. Putting case _: first is a SyntaxError (wildcard makes remaining patterns unreachable), not a silent shadow. Order still matters among the other patterns: put specific ones before general ones.
  • Positional class patterns need __match_args__. Use keyword patterns for classes that lack it.
  • Do not overuse it. A plain if/elif is clearer for a couple of simple comparisons.
  • It needs Python 3.10 or later. On 3.9 match is a SyntaxError. Older versions are covered in our Python 3.9 end-of-life guide. Code that uses match or case as variable names keeps working, because they are soft keywords.

Let a type checker find the missing case

Combine match with type hints and a type checker can tell you when you have missed a case. With mypy 2.4.1:

from typing import Literal, assert_never

Shape = Literal["circle", "square", "triangle"]

def sides(s: Shape) -> int:
    match s:
        case "circle":
            return 0
        case "square":
            return 4
        case _:
            assert_never(s)

mypy reports Argument 1 to "assert_never" has incompatible type "Literal['triangle']"; expected "Never". Without the final case _, it reports Missing return statement instead. Handling "triangle" as well removes the error. typing.assert_never exists from Python 3.11; on 3.10 import it from typing_extensions. See type checkers compared for choosing a checker.

When match is worth using

Parsing commands, handling messages or events of different shapes, walking syntax trees, and validating nested data. For one or two plain comparisons, if is still the better tool.

Frequently Asked Questions

What is the match statement in Python?

The match statement, added in Python 3.10 by PEP 634, compares a value against a series of patterns and runs the first block that fits. It is called structural pattern matching because patterns can destructure sequences, dictionaries and objects, not just compare values.

Is match the same as a switch statement?

It can do what a switch does, but it is more powerful. It can unpack lists and tuples, match dictionary shapes, check class attributes and bind names to the parts it matches. There is no fall-through and no break.

What does case _ mean in Python?

The underscore is a wildcard pattern that matches anything and binds nothing. Put it last as the default case: a wildcard before other cases is a SyntaxError because it makes the remaining patterns unreachable.

Which Python version added match?

Python 3.10. On Python 3.9 and earlier a match statement is a SyntaxError, which is another reason to upgrade from versions that have reached end of life. The words match and case are soft keywords, so they still work as variable names.

Why does my case pattern match everything?

A bare name in a pattern is a capture pattern: it matches anything and assigns it to that name. Directly in a case followed by other cases it raises a SyntaxError, but inside a larger pattern such as case (‘paint’, RED) it silently captures and overwrites the variable. To compare against a constant, use a dotted name such as Color.RED, or a literal.