match Statement
On this page
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:
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.
Example
Here is an example of a match
statement:
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:
Note
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:
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.