Statement

match / case

match compares one value against a list of case patterns and runs the first that fits. It needs Python 3.10 or newer.

IntermediateEvery example below runs in your browser. Change the code and press Run.

match subject: case pattern1: ... case pattern2 | pattern3: ... case _: # anything else

match looks at one value (the subject) and tries each case from top to bottom. The first pattern that fits wins and its block runs; the rest are skipped. case _: matches anything, so it works like a final else.

Patterns can do much more than compare with ==. They can check the shape of a list or tuple and pull out its parts, look for keys in a dictionary, test the type of an object, combine options with |, and add an extra condition with if.

It was added in Python 3.10, so older versions show a SyntaxError. One trap: a bare name in a pattern, like case total:, does not compare with a variable called total; it captures any value into that name.

Examples

1Like a switch on values

Pythoneditable
def http_status(code):
    match code:
        case 200:
            return "OK"
        case 404:
            return "Not found"
        case 500 | 502 | 503:
            return "Server error"
        case _:
            return "Other"

for c in [200, 503, 418]:
    print(c, http_status(c))
Output
200 OK
503 Server error
418 Other

2Pull apart a command

A list pattern matches only sequences (lists or tuples, not strings) of that length, and names in it capture the parts.

Pythoneditable
def run(command):
    match command.split():
        case ["go", direction]:
            return f"Moving {direction}"
        case ["pick", "up", item]:
            return f"Picked up the {item}"
        case ["quit"]:
            return "Bye"
        case _:
            return "Unknown command"

print(run("go north"))
print(run("pick up lamp"))
print(run("dance"))
Output
Moving north
Picked up the lamp
Unknown command

3Guards with if

Pythoneditable
def describe(point):
    match point:
        case (0, 0):
            return "origin"
        case (x, 0):
            return f"on the x axis at {x}"
        case (x, y) if x == y:
            return f"on the diagonal at {x}"
        case (x, y):
            return f"at {x}, {y}"

for p in [(0, 0), (5, 0), (3, 3), (1, 7)]:
    print(describe(p))
Output
origin
on the x axis at 5
on the diagonal at 3
at 1, 7

4Match dictionaries and types

Pythoneditable
events = [
    {"type": "order", "id": 17, "total": 59.9},
    {"type": "refund", "id": 17},
    {"type": "login"},
]
for e in events:
    match e:
        case {"type": "order", "total": float(total)}:
            print(f"Order of {total:.2f}")
        case {"type": "refund", "id": int(order_id)}:
            print("Refund for order", order_id)
        case {"type": other}:
            print("Ignored:", other)
Output
Order of 59.90
Refund for order 17
Ignored: login

A dictionary pattern only needs the listed keys; extra keys are allowed. float(total) checks the type and captures the value.

Common mistakes

Matching against a variable by name

A plain name in a case captures the value instead of comparing. Use a dotted name (a constant on a class or module) or a guard.

Pythoneditable
LIMIT = 100
value = 5
match value:
    case n if n == LIMIT:
        print("at the limit")
    case _:
        print("not at the limit")
Output
not at the limit

Using match on Python 3.9 or older

match is a SyntaxError before 3.10. On older versions use an if / elif chain.

Questions people ask

Is match the same as switch in other languages?

It covers what switch does, and more: it can also unpack lists, tuples, dictionaries and objects. There is no fall-through, so no break is needed.

What does case _ mean?

_ is the wildcard: it matches anything and stores nothing. Put it last as a catch-all.

match or if/elif?

For a few simple comparisons, if / elif is fine. match shines when you check the shape of data and need its parts.

Spotted a mistake on this page? Tell us