Browse Python Topics ▼
Pick a Web Framework

Match Case and Pattern Matching

📂 Control Flow 📘 Lesson 14 of 57

Master structural pattern matching in Python 3.10+ using match and case statements, literal patterns, sequence deconstruction, guards, and wildcard fallbacks.

For decades, developers coming to Python from languages like C, Java, or JavaScript asked the same question: “Where is Python’s switch statement?”

Until Python 3.10, Python deliberately avoided a traditional switch statement. Developers used chains of if-elif-else statements or dictionaries. But in Python 3.10, Python introduced something far more capable than a simple switch statement: Structural Pattern Matching using the match and case keywords.

While a traditional switch statement merely compares a single value against constants (value == 1), Python’s pattern matching inspects both the shape (structure) and the contents of your data, unpacking components and binding them to variables in a single expressive step.


1. The Anatomy of a match Statement

At its simplest, match-case works like an elegant, readable alternative to a cascading if-elif-else ladder.

status_code = 404

match status_code:
    case 200:
        print("Success: OK")
    case 400:
        print("Client Error: Bad Request")
    case 404:
        print("Client Error: Resource Not Found")
    case 500:
        print("Server Error: Internal Failure")
    case _:
        # The wildcard underscore matches anything not handled above
        print("Unhandled HTTP Status Code")

Output:

Client Error: Resource Not Found

Key Rules of match-case:

  1. The match header: Evaluates the subject expression once (match status_code:).
  2. Sequential evaluation: Python tests each case branch from top to bottom. As soon as the first pattern matches, Python executes that block and immediately exits the match statement.
  3. No break statements required: Unlike C, Java, or JavaScript where cases “fall through” unless you explicitly type break;, Python never falls through.
  4. The Wildcard (_): An underscore case _: acts as a catch-all fallback. It matches any value and is equivalent to the final else: branch in an if statement.

2. Combining Patterns with the Pipe (|)

If multiple values should trigger the exact same logic, combine them using the vertical pipe character (|), which acts as an OR operator:

weekday = "Saturday"

match weekday:
    case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":
        print("It is a working weekday. Time to code!")
    case "Saturday" | "Sunday":
        print("It is the weekend! Time to recharge.")
    case _:
        print("Not a valid day name.")

Output:

It is the weekend! Time to recharge.

3. Structural Deconstruction: Unpacking Sequences

The true power of structural pattern matching becomes apparent when working with complex data structures like lists and tuples. Python can inspect the length of a sequence and unpack its elements into named variables simultaneously.

Imagine writing a text parser for a terminal game or command-line utility:

def process_command(command):
    match command:
        # Matches a list with exactly one item: "quit"
        case ["quit"]:
            print("Shutting down the game engine...")

        # Matches a 2-item list starting with "look"
        case ["look", target]:
            print(f"You inspect the {target} closely.")

        # Matches a 3-item list starting with "transfer"
        case ["transfer", amount, recipient]:
            print(f"Transferring ${amount} to account '{recipient}'...")

        # Matches any list starting with "broadcast", gathering everything else into a list
        case ["broadcast", *messages]:
            print(f"Broadcasting to everyone: {' '.join(messages)}")

        case _:
            print(f"Error: Unknown command sequence {command}")

# Test different shapes and commands:
process_command(["look", "treasure chest"])
process_command(["transfer", 250, "Alice"])
process_command(["broadcast", "Server", "maintenance", "in", "5m"])
process_command(["quit"])

Output:

You inspect the treasure chest closely.
Transferring $250 to account 'Alice'...
Broadcasting to everyone: Server maintenance in 5m
Shutting down the game engine...

Notice what happened in case ["look", target]:! Python verified that:

  1. command is a sequence.
  2. command contains exactly two elements.
  3. The first element is the literal string "look".
  4. If all three criteria matched, Python automatically extracted the second item and assigned it to the brand new variable target!

4. Pattern Guards: Adding if Conditions

Sometimes matching the shape is not enough; you also need to validate a dynamic condition on the unpacked values. You can attach a guard condition to any case using the if keyword:

coordinates = (15, -4)

match coordinates:
    case (0, 0):
        print("Point is at the exact origin.")
    case (x, 0):
        print(f"Point lies on the X-axis at {x}")
    case (0, y):
        print(f"Point lies on the Y-axis at {y}")
    case (x, y) if x > 0 and y > 0:
        print(f"Point ({x}, {y}) is in Quadrant I (top-right)")
    case (x, y) if x < 0 and y > 0:
        print(f"Point ({x}, {y}) is in Quadrant II (top-left)")
    case (x, y) if x < 0 and y < 0:
        print(f"Point ({x}, {y}) is in Quadrant III (bottom-left)")
    case (x, y) if x > 0 and y < 0:
        print(f"Point ({x}, {y}) is in Quadrant IV (bottom-right)")
    case _:
        print("Invalid coordinate format.")

Output:

Point (15, -4) is in Quadrant IV (bottom-right)

[!NOTE] Python only tests the guard (if x > 0 and y < 0) after the structural match (x, y) succeeds. If the guard evaluates to False, Python does not abort; it simply moves on to test the next case branch.


5. Capturing Patterns with as

If you want to match a sub-pattern while still keeping a reference to the whole structure, use the as keyword:

event = ["click", (120, 480)]

match event:
    case ["click", (int(x), int(y)) as point]:
        print(f"Mouse clicked at coordinates {point}: X={x}, Y={y}")
    case _:
        print("Unsupported event")

Here, point receives the tuple (120, 480), while x and y receive 120 and 480 respectively.


6. Common Traps & Gotchas

Trap 1: Variable Names Are Capture Patterns, NOT Equality Checks!

This is the number one mistake beginners make when using match-case:

# Intended: Check if response equals the constant EXPECTED_CODE
EXPECTED_CODE = 200
response = 404

match response:
    case EXPECTED_CODE:  # WARNING: This does NOT compare response == EXPECTED_CODE!
        print("Matched expected code!")

Why does this print "Matched expected code!" even though response is 404? In Python pattern matching, a plain variable name like EXPECTED_CODE inside a case statement is treated as a capture variable. It rebinds the variable EXPECTED_CODE to the value of response (404) and matches unconditionally!

The Fix: To match against external constants or enumeration values, use dotted names or a guard:

import http

response = 404

match response:
    # Dotted names are treated as equality lookups, not variable bindings
    case http.HTTPStatus.OK:
        print("Success 200")
    case _ if response == EXPECTED_CODE:
        print("Matched custom constant")
    case _:
        print("Different response code")

Trap 2: Catch-All case _ Must Be Last

Because case _: matches literally every value, placing it anywhere before other case statements will cause Python to raise a SyntaxError: wildcard makes remaining patterns unreachable.


7. match-case vs if-elif-else: When to Use Which?

Feature / Goalif-elif-elsematch-case
Simple range checks (e.g. score >= 80)Ideal and conciseClunky; requires awkward guards
Boolean flags (e.g. if is_admin:)Best practiceOverkill
Parsing command inputs & sequencesVerbose (len(cmd) == 2 and cmd[0] == ...)Beautiful, declarative unpacking
Matching structured payloads (APIs, ASTs)Nested and error-proneClean, self-documenting
Python Version SupportAll Python versions (Python 1.0+)Requires Python 3.10+

Summary & Practice

  • Structural pattern matching with match ... case deconstructs data shapes and values simultaneously.
  • Wildcard case _: serves as the default fallback branch.
  • Combine values with | (OR) and constrain patterns using if guards.
  • Never use a bare identifier expecting an equality check; bare identifiers bind variables.

Next, master how to repeat execution automatically across sequences and conditions in loops.

Test your understanding of Match Case and Pattern Matching

Quick interactive practice questions with instant feedback.

Take Quiz →