CodeMIRAI
0 XP

The match statement

2 min read 4 runnable examples Quiz included

When you compare one value against many possibilities, a long if/elif chain gets repetitive. Since Python 3.10, the match statement handles this cleanly.

Matching literal values

Python
command = "stop"

match command:
    case "start":
        print("Starting the engine")
    case "stop":
        print("Stopping")
    case "pause":
        print("Pausing")
    case _:
        print("Unknown command")

Python compares the value with each case in order and runs the first one that matches. The underscore _ is a wildcard that matches anything, like a final else.

Several values in one case

Use | ("or") to match any of several values:

Python
day = "Sun"

match day:
    case "Sat" | "Sun":
        print("Weekend!")
    case "Mon" | "Tue" | "Wed" | "Thu" | "Fri":
        print("Weekday")
    case _:
        print("Not a day")

Guards

Add if to a case to check an extra condition:

Python
temperature = 38

match temperature:
    case t if t >= 40:
        print("Extreme heat warning")
    case t if t >= 30:
        print("Hot")
    case t if t >= 15:
        print("Pleasant")
    case _:
        print("Cold")

Here t is a capture pattern: it matches anything and gives it a name to use in the guard and the block.

Matching structure

match can look inside lists and tuples, which is where it really shines:

Python
points = [(0, 0), (3, 0), (0, 4), (2, 5)]

for point in points:
    match point:
        case (0, 0):
            print("Origin")
        case (x, 0):
            print(f"On the x-axis at {x}")
        case (0, y):
            print(f"On the y-axis at {y}")
        case (x, y):
            print(f"At ({x}, {y})")

Each pattern checks the shape and pulls out the values in one step.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.