Ad – 728Γ—90
πŸ”€ Control Flow

Python Match Case – Pattern Matching (Python 3.10+)

Python 3.10 introduced the match statement β€” Python's version of switch/case found in other languages, but far more powerful. It supports structural pattern matching: matching against values, types, sequences, mappings, and object attributes. It requires Python 3.10 or newer.

⏱️ 20 min read 🎯 Intermediate πŸ“… Updated 2026

Basic Match-Case Syntax

The match statement compares a value against multiple patterns. The first matching pattern executes its block. The case _: is the wildcard (matches anything β€” like "else").

Python
def describe_http_status(status):
    match status:
        case 200:
            return "OK"
        case 404:
            return "Not Found"
        case 500:
            return "Server Error"
        case _:              # wildcard - matches anything
            return f"Unknown status: {status}"

print(describe_http_status(200))
print(describe_http_status(404))
print(describe_http_status(999))
β–Ά Output
OK Not Found Unknown status: 999

OR Patterns – Multiple Values

Use | to match multiple values in a single case.

Python
def day_type(day):
    match day:
        case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":
            return "Weekday"
        case "Saturday" | "Sunday":
            return "Weekend"
        case _:
            return "Invalid day"

print(day_type("Monday"))    # Weekday
print(day_type("Saturday"))  # Weekend
β–Ά Output
Weekday Weekend
Ad – 336Γ—280

Guard Conditions with if

Add an if guard to a case for additional conditions.

Python
def classify(value):
    match value:
        case x if x < 0:
            return f"{x} is negative"
        case 0:
            return "zero"
        case x if x > 0 and x <= 100:
            return f"{x} is between 1 and 100"
        case _:
            return f"{value} is over 100"

print(classify(-5))
print(classify(0))
print(classify(42))
β–Ά Output
-5 is negative zero 42 is between 1 and 100

Matching Sequences and Dicts

Match can destructure lists, tuples, and dicts directly.

Python
# Match sequences (lists/tuples)
def describe_point(point):
    match point:
        case [0, 0]:
            return "Origin"
        case [x, 0]:
            return f"On X-axis at {x}"
        case [0, y]:
            return f"On Y-axis at {y}"
        case [x, y]:
            return f"Point at ({x}, {y})"

print(describe_point([0, 0]))
print(describe_point([3, 0]))
print(describe_point([4, 5]))
β–Ά Output
Origin On X-axis at 3 Point at (4, 5)