Python match-case and Pattern Matching

Learn Python match-case and Pattern Matching with practical examples, explanations, best practices, and real-world coding techniques.

The Python match-case statement provides a structured way to compare a value or object against multiple patterns and execute the first matching block. It was introduced in Python 3.10 as part of structural pattern matching and is useful when a program needs to make decisions based on the shape or structure of data, not only on simple equality checks.

Developers who are familiar with switch statements in other languages may initially think of match as simply Python's version of switch. That comparison is useful as a starting point, but Python's pattern matching can do much more. A case can match a literal value, several values, a sequence, a dictionary-like structure, a class, or a pattern with additional conditions.

Match-case is especially useful when several possible shapes or states need to be handled clearly. For simple true-or-false decisions, if, elif, and else are often easier to read. Choosing between the two should depend on the structure of the decision you are trying to express.

Basic match-case Syntax

A match statement evaluates a subject and checks it against one or more case patterns.

status = "paid"

match status:
    case "paid":
        print("Order can be processed")
    case "pending":
        print("Waiting for payment")
    case "cancelled":
        print("Order was cancelled")
    case _:
        print("Unknown status")

Python evaluates the cases from top to bottom. When a pattern matches, that case is selected and its block is executed. The underscore _ is commonly used as a wildcard that matches anything and is useful as a final fallback case.

match-case vs if-elif-else

Both match-case and if-elif-else can be used for decision making, but they solve slightly different problems. An if statement is naturally suited to arbitrary boolean conditions, while match-case is particularly useful when you want to describe expected patterns in a value or object.

if / elif match / case
Best for general boolean conditions Best for matching values and structures
Conditions can be arbitrary expressions Uses structural patterns
Common for ranges and complex boolean rules Useful for commands, states, sequences, mappings, and object shapes
Often simpler for a small number of ordinary conditions Can make structured matching easier to read

For example, checking whether an age is greater than a minimum value is usually more natural with if. Matching a command such as "start", "stop", or "pause" can be a good fit for match.

Matching Multiple Values

A single case can match multiple alternatives using the | pattern operator.

command = "start"

match command:
    case "start" | "resume":
        print("Starting process")
    case "stop" | "cancel":
        print("Stopping process")
    case _:
        print("Unknown command")

This can make related cases easier to understand without duplicating the same block of code.

The Wildcard Case

The underscore pattern _ matches any value that has not matched an earlier case. It is useful when the program needs a default behavior.

role = "viewer"

match role:
    case "admin":
        print("Full access")
    case "editor":
        print("Edit access")
    case _:
        print("Limited access")

The wildcard should normally appear after the more specific patterns. Once it matches, later cases cannot be reached.

Capturing Values with Patterns

One of the important features of structural pattern matching is that a pattern can capture information from the matched value.

command = ("create", "user")

match command:
    case ("create", name):
        print("Create:", name)
    case ("delete", name):
        print("Delete:", name)

In this example, the second value is captured into name when the tuple matches the corresponding pattern.

This is different from simply comparing a complete tuple for equality. The pattern describes the expected structure and extracts useful pieces from it at the same time.

Matching Lists and Sequences

Match-case can inspect the structure of sequences such as lists and tuples. This is useful when the number or arrangement of values has meaning.

values = [10, 20]

match values:
    case [10, 20]:
        print("Exact values matched")
    case [first, second]:
        print("Two values:", first, second)
    case []:
        print("Empty list")
    case _:
        print("Different structure")

The pattern can therefore express both content and structure. This is useful for parsing commands, processing structured results, and handling different forms of input.

Capturing Remaining Sequence Values

The star pattern can capture multiple remaining values from a sequence. This is useful when the beginning or end of a sequence matters but the exact number of middle elements can vary.

values = [1, 2, 3, 4, 5]

match values:
    case [first, *middle, last]:
        print("First:", first)
        print("Middle:", middle)
        print("Last:", last)

Here, the first and last elements are captured separately while the values in between are collected into middle.

Matching Dictionaries

Match-case can also work with mappings such as dictionaries. This makes it useful when application data has a known structure.

request = {
    "type": "user",
    "role": "admin"
}

match request:
    case {"type": "user", "role": "admin"}:
        print("Administrator request")
    case {"type": "user", "role": role}:
        print("User role:", role)
    case _:
        print("Unknown request")

The pattern can match required keys and capture the values associated with them. This can be particularly useful when processing structured data from configuration, messages, or application logic.

A mapping pattern does not mean that every key must be specified. The pattern describes the parts of the mapping that need to match.

Guard Conditions with if

A case can include an additional condition called a guard. The pattern must match first, and then the guard must also evaluate to true.

score = 85

match score:
    case value if value >= 90:
        print("Excellent")
    case value if value >= 75:
        print("Good")
    case value if value >= 60:
        print("Pass")
    case _:
        print("Needs improvement")

Guards are useful when matching alone is not enough and the application needs an additional condition. However, if the logic consists mainly of arbitrary ranges and boolean expressions, a traditional if/elif structure may communicate the intention more directly.

Matching Object Structures

Structural pattern matching can also be used with classes. This makes it possible to match the type and selected attributes of an object, which can be useful when working with structured domain objects.

class User:
    def __init__(self, name, role):
        self.name = name
        self.role = role

user = User("Asha", "admin")

match user:
    case User(name, "admin"):
        print(f"{name} is an administrator")
    case User(name, role):
        print(f"{name} has role {role}")

Class patterns are more advanced than literal matching, but they show why Python's match statement is more powerful than a traditional switch-style construct. The program can describe the expected structure of an object and capture relevant information at the same time.

Matching Constants and Enums

Match-case can be useful when an application has a small, known set of states. For example, an application may represent an order lifecycle using constants or an enumeration.

status = "shipped"

match status:
    case "pending":
        print("Waiting for processing")
    case "paid":
        print("Payment completed")
    case "shipped":
        print("Order is on the way")
    case "delivered":
        print("Order delivered")
    case _:
        print("Unknown status")

This pattern can make state-based workflows easier to read when the possible values are well defined.

Match-Case and Command Handling

A practical use case for match-case is handling commands from a CLI tool or another part of an application.

command = "status"

match command:
    case "start":
        print("Starting application")
    case "stop":
        print("Stopping application")
    case "restart":
        print("Restarting application")
    case "status":
        print("Application is running")
    case _:
        print("Unknown command")

As the number of supported commands increases, the match statement keeps the alternatives in one predictable structure. This can be clearer than a long chain of equality comparisons.

When Should You Use match-case?

Match-case is most useful when the decision naturally describes different patterns or states. It is particularly valuable when the input has a known structure and the matching logic would otherwise require repeated comparisons or nested conditions.

  • Handling a known set of commands or application states.
  • Matching tuples, lists, and other sequence structures.
  • Processing structured dictionary data.
  • Extracting values while matching a known pattern.
  • Matching different object shapes or classes.
  • Replacing a long series of simple equality checks with clearer case branches.

It is usually less useful when the problem is primarily about arbitrary boolean conditions, numeric ranges, or a small number of straightforward comparisons. In those situations, if and elif may be simpler.

Common match-case Mistakes

Treating match as Only a Switch Statement

Python pattern matching can inspect structure and capture values. Limiting it to simple equality checks misses one of its main strengths.

Putting a Broad Pattern Too Early

Cases are evaluated in order. A broad pattern can match before a more specific case, making the later branch unreachable.

Using Complex Guards for Simple Conditions

If most of the logic consists of ordinary comparisons and boolean expressions, if and elif may be easier to understand.

Forgetting the Fallback Case

A _ case is optional, but it can be useful when unknown values need explicit handling.

Making Patterns Harder to Read Than the Original Code

Pattern matching is powerful, but complex patterns are not automatically better. Prefer the approach that communicates the decision most clearly.

Practical Example: API Request Routing

Match-case can also be useful when an application needs to interpret structured commands or requests.

request = {
    "action": "create",
    "resource": "user",
    "name": "Asha"
}

match request:
    case {
        "action": "create",
        "resource": "user",
        "name": name
    }:
        print(f"Creating user: {name}")

    case {
        "action": "delete",
        "resource": "user",
        "name": name
    }:
        print(f"Deleting user: {name}")

    case _:
        print("Unsupported request")

Instead of checking each dictionary key separately, the pattern describes the structure expected for each operation. This can make structured decision logic easier to follow when the request formats are well defined.

Best Practices for Python match-case

  • Use match-case when the problem is naturally expressed as pattern matching rather than forcing ordinary conditions into patterns.
  • Put specific cases before broader matching patterns.
  • Use the wildcard _ for a clear fallback when unknown values need handling.
  • Use captured values when the matched structure provides information that the program needs to process.
  • Keep patterns readable and avoid unnecessary complexity.
  • Prefer if and elif when arbitrary boolean conditions express the requirement more clearly.
  • Test both expected patterns and unexpected input so that unmatched cases behave safely.

Why match-case Matters

The Python match-case statement gives developers a concise way to express structured decisions. Its main value is not simply replacing a long if-elif chain. Structural pattern matching allows Python code to recognize the shape of data and extract useful values while performing the match.

For simple conditions, traditional conditional statements remain a good choice. For structured commands, sequences, mappings, object patterns, and state-based logic, match-case can provide a clearer representation of the problem.

As you become more comfortable with Python, learning match-case gives you another tool for expressing decision logic. The important skill is knowing when its pattern-matching model makes the code easier to understand rather than using it simply because it is a newer language feature.

Code Examples

Basic match-case

python
status = "paid"

match status:
    case "paid":
        print("Order can be processed")
    case "pending":
        print("Waiting for payment")
    case "cancelled":
        print("Order was cancelled")
    case _:
        print("Unknown status")
    

Matching multiple values

python
command = "resume"

match command:
    case "start" | "resume":
        print("Starting process")
    case "stop" | "cancel":
        print("Stopping process")
    case _:
        print("Unknown command")
    

Matching a sequence

python
values = [10, 20, 30]

match values:
    case [first, *middle, last]:
        print("First:", first)
        print("Middle:", middle)
        print("Last:", last)
    case _:
        print("Different structure")
    

Matching dictionary data

python
request = {
    "type": "user",
    "role": "admin"
}

match request:
    case {"type": "user", "role": "admin"}:
        print("Administrator request")
    case {"type": "user", "role": role}:
        print("User role:", role)
    case _:
        print("Unknown request")
    

Pro Tip

Think of match-case as pattern matching, not just Python switch syntax. Use it when the shape or structure of the data is part of the decision, and prefer if-elif when ordinary boolean conditions are clearer.

More Python lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.