match Statement

The match statement was introduced in Python 3.10 as a tool for structural pattern matching. It works similarly to switch statements in other programming languages, allowing you to match patterns within data and execute specific code blocks accordingly. It offers a more expressive and readable alternative to nested if-elif-else statements when dealing with complex data types.

Basic Syntax

The basic syntax of the match statement in Python is as follows:

1match expression:
2    case pattern1:
3        <statements>
4    case pattern2:
5        <statements>
6    ...
7    case patternN:
8        <statements>

Here, expression is the value to be matched, and pattern1, pattern2, …, patternN are patterns to test against the expression. The corresponding block of <statements> will be executed when a match is found.


Here is an example of a match statement:

 1def match_demo(expression):
 2    match expression:
 3        case 1:
 4            return "One"
 5        case 2:
 6            return "Two"
 7        case 3:
 8            return "Three"
 9        case _:
10            return "Unknown"

In this example, the function match_demo takes an argument expression, which it matches against the integers 1, 2, and 3. The case _ is a catch-all pattern for unmatched cases.

When we call match_demo with various inputs, we get:

1print(match_demo(1))  # returns: One
2print(match_demo(2))  # returns: Two
3print(match_demo(3))  # returns: Three
4print(match_demo(5))  # returns: Unknown


In Python, the _ variable is often used as a throwaway variable (i.e., for values that will be discarded and not used again). In the context of match statements, _ can be used as a catch-all pattern.

More Complex Patterns

match statements are not just limited to matching numbers or other simple values; they can also match more complex data types, like tuples and lists. Here is an example:

 1def match_demo(expression):
 2    match expression:
 3        case ('dog', 'bark'):
 4            return "Dogs bark."
 5        case ('cat', 'meow'):
 6            return "Cats meow."
 7        case _:
 8            return "Unknown animal or sound."
10print(match_demo(('dog', 'bark')))  # returns: Dogs bark.
11print(match_demo(('cat', 'purr')))  # returns: Unknown animal or sound.

In this case, expression is a tuple, and the match statement attempts to match it with other tuples.

match statements are a powerful and flexible tool for controlling the flow of your Python programs based on patterns in your data.