Academic Block

Python match / case StatementGet Certified

What Is match / case?

The match statement compares one value against a list of patterns and runs the block of the first pattern that fits. It was added in Python 3.10 and is called structural pattern matching. In its simplest form it works like the switch statement of other languages, but it is far more powerful. A pattern can describe the shape of data: a list with three items, a dictionary with certain keys, or an object of a certain class, and it can pick the parts out of that data into variables at the same time.

  • Literal patterns: match exact numbers, strings, True, False, and None.
  • Wildcard _: matches anything and works like a final else.
  • OR patterns: case "Sat" | "Sun": matches any of several alternatives.
  • Capture patterns and guards: store the matched value in a variable and add an extra if test.
  • Sequence, mapping and class patterns: take apart lists, tuples, dictionaries, and objects.
Note: match needs Python 3.10 or later. In older versions it is a SyntaxError. The code on this page runs in the browser with a modern Python runtime, so you do not need to install anything.

The Basic Syntax and Literal Patterns

A match statement starts with the keyword match, the value to inspect, and a colon. Each case below it, indented one level, holds a pattern and a colon, followed by an indented block. Python tests the cases from top to bottom and runs only the first one that matches. There is no fall-through, so you never need a break. The pattern _, called the wildcard, matches everything, so it is used as the last case for “none of the above”. If no case matches and there is no wildcard, nothing happens and no error is raised.

Try It: A Status Code Lookup

Click Test My Code. Change status to 500, and then to 301, and run it again.

What this code does: It compares an HTTP status code with three literal numbers and prints a description for the first one that matches. The wildcard case handles every other number.
status = 404
match status:
    case 200:
        print("OK")
    case 404:
        print("Not Found")
    case 500:
        print("Server Error")
    case _:
        print("Unknown status")

OR Patterns

Use the vertical bar | to match one of several alternatives in a single case. This avoids repeating the same block many times. Writing case "Sat" or "Sun": is not correct. The keyword or is evaluated as an ordinary expression and does not make a pattern. Always use | inside patterns.

Try It: Weekday or Weekend

Click Test My Code. Change day to "Wed" and then to "Holiday".

What this code does: It groups five weekday names into one case and two weekend names into another using |. Any other text reaches the wildcard.
day = "Sat"
match day:
    case "Mon" | "Tue" | "Wed" | "Thu" | "Fri":
        print("Weekday")
    case "Sat" | "Sun":
        print("Weekend")
    case _:
        print("Not a day")

Capture Patterns and Guards

A pattern that is a plain variable name, such as n, matches any value and stores it in that variable. This is a capture pattern. It is useful together with a guard, an if condition placed after the pattern. The case runs only when the pattern matches and the guard is true. If the guard is false, Python simply tries the next case.

  • A capture pattern always matches, so a case with one and no guard must be the last case. Python raises a SyntaxError if a later case could never be reached.
  • The wildcard _ is a capture pattern that does not store anything.
  • A bare name captures, it does not compare. To compare with a constant, use a dotted name such as Color.RED, or a literal.

Try It: Classifying a Number

Click Test My Code. Try number = -3, number = 0, and number = 8.

What this code does: It checks for zero with a literal pattern. It then captures the number in the variable n and uses guards to test whether it is negative or even. The final capture pattern handles the remaining odd positive numbers.
number = 15
match number:
    case 0:
        print("Zero")
    case n if n < 0:
        print(n, "is negative")
    case n if n % 2 == 0:
        print(n, "is even")
    case n:
        print(n, "is odd")

Sequence Patterns

A pattern written like a list or a tuple matches a sequence with the same number of items. Each item of the pattern can be a literal, which must be equal, or a variable name, which captures the item. A starred name such as *rest captures all the remaining items as a list. Both [a, b] and (a, b) match lists and tuples alike. Strings and bytes are the exception: they are never matched by sequence patterns, so a string is not split into characters by match.

Try It: A Command Interpreter

Click Test My Code. Add the command ["say", "hi"] to the list and run it again.

What this code does: It goes through four commands, each written as a list. A pattern matches the length of the list and the first word, captures the other parts in variables, and collects any number of words with a starred name.
commands = [["quit"], ["move", 3, 4], ["say", "hello", "world"], ["jump"]]
for command in commands:
    match command:
        case ["quit"]:
            print("Bye")
        case ["move", x, y]:
            print(f"Moving to ({x}, {y})")
        case ["say", *words]:
            print("Saying:", " ".join(words))
        case _:
            print("Unknown command")

Try It: Points on a Grid

Click Test My Code. Notice that the order of the cases matters: the most specific case, (0, 0), comes first.

What this code does: It examines four coordinate pairs. A pattern mixes literal numbers and variable names, so it can tell whether a point is on an axis and capture the other coordinate.
for data in [(0, 0), (5, 0), (0, 7), (2, 3)]:
    match data:
        case (0, 0):
            print("Origin")
        case (x, 0):
            print("On the x-axis at", x)
        case (0, y):
            print("On the y-axis at", y)
        case (x, y):
            print("Point", x, y)

Mapping Patterns

A pattern written like a dictionary matches a mapping that contains at least the listed keys. The keys in the pattern must be literals, and each value can be a literal or a variable name that captures the value. Unlike sequence patterns, a mapping pattern ignores extra keys, so the dictionary may contain more entries than the pattern mentions. To collect the extra entries, finish the pattern with **rest.

Try It: Handling Events

Click Test My Code. Change the event to {"type": "key", "key": "Enter"} and run it again.

What this code does: It describes a mouse click as a dictionary. The first case requires the value "click" under the key "type" and captures the coordinates. The second case handles keyboard events.
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("Key pressed:", key)
    case _:
        print("Unknown event")

Type and Class Patterns

A pattern that looks like a call, such as int() or str(), checks the type of the value, in the same way as isinstance(). Because it uses isinstance() rules, a class pattern also matches subclasses. This matters for bool, which is a subclass of int: case int(): would also match True, so test bool() first.

The same syntax works with your own classes. Inside the parentheses you can match attributes by name, as in Point(x=0, y=0). Classes created with @dataclass also allow positional patterns, such as Point(0, y).

Try It: Matching by Type

Click Test My Code. Move case bool(): below case int():, run it again, and see how the result for True changes.

What this code does: It goes through six values of different types. Each class pattern tests the type of the value, and the program prints the type name together with the value, or with the length of a list.
values = [42, "hello", 3.5, [1, 2], None, True]
for value in values:
    match value:
        case None:
            print("None")
        case bool():
            print("bool", value)
        case int():
            print("int", value)
        case float():
            print("float", value)
        case str():
            print("str", value)
        case list():
            print("list of", len(value))
        case _:
            print("other")

Try It: Matching Objects

Click Test My Code. Change the point to Point(3, 0) and then to Point(2, 2).

What this code does: It defines a small Point class with @dataclass and creates one object. Class patterns then check the attributes of the object by name and capture the one that is not fixed.
from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

p = Point(0, 5)
match p:
    case Point(x=0, y=0):
        print("Origin")
    case Point(x=0, y=y):
        print("On the y-axis at", y)
    case Point(x=x, y=0):
        print("On the x-axis at", x)
    case Point():
        print("Somewhere else")
Tip: Put the most specific pattern first and the most general one last. A general pattern placed early would match first and hide the specific ones below it. Use if / elif for simple true/false tests, and use match when you compare one value against many shapes or want to unpack data while you test it.

Using match with User Input

The match statement is a natural fit for programs that read commands. Remember that input() returns a string, and that a string is not matched by sequence patterns. Use split() to turn the line into a list of words first, then write patterns for the lists you expect.

Try It: A Four-Function Calculator

The Program Input box is already filled with 12 * 3. Click Run Code straight away, then try 10 / 0, 7 - 2, and hello.

What this code does: It reads an expression such as 12 * 3 and splits it into three words. A pattern for each operator captures the two numbers as text, and the program converts them to floats. A guard stops a division by zero, and the wildcard reports a wrong format.
expression = input("Enter e.g. 12 + 3: ").split()
match expression:
    case [a, "+", b]:
        print(float(a) + float(b))
    case [a, "-", b]:
        print(float(a) - float(b))
    case [a, "*", b]:
        print(float(a) * float(b))
    case [a, "/", b] if float(b) != 0:
        print(float(a) / float(b))
    case [_, "/", _]:
        print("Cannot divide by zero")
    case _:
        print("Use the form: number operator number")

Try It: A Text Adventure Parser

The Program Input box is filled with go north. Click Run Code, then try take lamp, go up, exit, and an empty box.

What this code does: It reads a command, cleans it, and splits it into words. Patterns recognize a movement in four directions, a command to take an item, two ways to quit, and an empty line. The as keyword stores the matched direction in a variable.
command = input("Enter a command: ").strip().lower().split()
match command:
    case ["go", ("north" | "south" | "east" | "west") as direction]:
        print("You walk", direction)
    case ["take", item]:
        print("You take the", item)
    case ["quit" | "exit"]:
        print("Goodbye")
    case []:
        print("Please type something")
    case _:
        print("Unknown command")

Common Mistakes with match / case

  • Using Python older than 3.10: match raises a SyntaxError. Check your version with python --version.
  • Expecting a bare name to compare: case RED: does not compare with a variable called RED. It captures the value into a new variable named RED and always matches. Use a dotted name such as Color.RED or a literal.
  • Using or instead of |: write case "a" | "b":. An OR pattern also cannot bind different variable names on each side.
  • Putting a catch-all case first: a capture pattern without a guard matches everything, and Python reports a SyntaxError when it hides later cases. Place case _: last.
  • Forgetting the wildcard: when nothing matches and there is no case _:, the statement silently does nothing.
  • Wrong order of patterns: a general pattern before a specific one hides the specific one. Test bool() before int(), and (0, 0) before (x, y).
  • Matching a string like a list: a string is never matched by a sequence pattern. Split it first, or compare it as a whole with a literal pattern.
  • Expecting fall-through or needing break: only the first matching case runs, and Python leaves the statement at once. No break is needed.

Key Takeaways

  • match compares a value with patterns from top to bottom and runs only the first case that matches.
  • The wildcard _ matches anything and is used as the final “none of the above” case.
  • Use | to combine alternatives, and an if guard to add an extra condition to a case.
  • A plain variable name in a pattern captures a value. It does not compare with an existing variable.
  • Sequence patterns take apart lists and tuples, mapping patterns take apart dictionaries, and class patterns check types and attributes.
  • Strings are not matched as sequences, and mapping patterns ignore extra keys.
  • match requires Python 3.10 or later. For simple true/false decisions, if / elif / else is still the right tool.

Frequently Asked Questions

What is the match case statement in Python?

The match statement compares a value with a series of patterns written as case blocks and runs the block of the first pattern that matches. It is called structural pattern matching and was added in Python 3.10. A pattern can be a simple literal or the shape of a list, a dictionary, or an object.

Which Python version supports match case?

Python 3.10 and later. In Python 3.9 and earlier, the match statement raises a SyntaxError, so use an if, elif, else chain instead.

Is match case the same as a switch statement?

It can be used like a switch statement to choose between several values, but it is more powerful. It also matches the structure of lists, tuples, dictionaries, and objects, captures parts of the data into variables, and supports guards. There is no fall-through, so no break statement is needed.

What does case _ mean in Python?

The underscore is the wildcard pattern. It matches any value and does not store it, so case _ works like the final else of an if chain. It should be the last case. If no case matches and there is no wildcard, the match statement does nothing.

How do I match multiple values in one case?

Join the alternatives with the vertical bar, for example case “Sat” | “Sun”:. This is an OR pattern. Do not use the keyword or inside a pattern, because it does not create an OR pattern.

What is a guard in a Python case statement?

A guard is an if condition placed after a pattern, as in case n if n < 0:. The case runs only when the pattern matches and the guard is true. If the guard is false, Python tries the next case.

Can match case work with dictionaries and classes?

Yes. A mapping pattern such as {“type”: “click”, “x”: x} matches a dictionary that contains those keys and captures the values, and it ignores extra keys. A class pattern such as Point(x=0, y=y) checks the type of an object and its attributes.

Should I use match case or if elif else?

Use if, elif, else for simple true or false conditions and ranges of numbers. Use match case when you compare one value with many literals, or when you need to take apart structured data such as lists, tuples, dictionaries, and objects while you test it.

Ready for the next step?Learn how to repeat actions with loops.
Next: for Loops & range() →