Control Flow

Tutorial for python match statement using easy examples

The match statement, introduced in Python 3.10, brings pattern matching to Python. It allows you to destructure data and execute code based on the structure and value of the data. It’s similar to a more powerful switch statement seen in other programming languages. Here’s a step-by-step guide to help you understand Python’s match statement.

Step 1: Basic Syntax

The basic syntax of a match statement is:

Python
match expression:
    case pattern1:
        # code to execute if pattern1 matches
    case pattern2:
        # code to execute if pattern2 matches
    case _:
        # code to execute if no patterns match (equivalent to 'default' in some languages)

Step 2: Simple Example

Here’s a basic example using integers:

Python
x = 2

match x:
    case 1:
        print("x is 1")
    case 2:
        print("x is 2")
    case _:
        print("x is neither 1 nor 2")

Output:

x is 2

Step 3: Using Sequence Patterns

You can also match against the elements in lists or tuples:

Python
my_list = [1, 2, 3]

match my_list:
    case []:
        print("The list is empty.")
    case [1, 2, 3]:
        print("The list contains 1, 2, 3.")
    case _:
        print("The list contains other elements.")

Output:

The list contains 1, 2, 3.

Step 4: Using Wildcards

You can use the _ wildcard to match any value:

Python
x = "hello"

match x:
    case 1:
        print("x is 1")
    case _:
        print("x is not 1")

Output:

x is not 1

Step 5: Destructuring Data

You can destructure data within the pattern:

Python
point = (2, 3)

match point:
    case (0, 0):
        print("Origin")
    case (0, y):
        print(f"Point is on the Y-axis at {y=}")
    case (x, 0):
        print(f"Point is on the X-axis at {x=}")
    case (x, y):
        print(f"Point is at {x=}, {y=}")
    case _:
        print("Not a point")

Output:

Point is at x=2, y=3

Step 6: Using OR | Patterns

You can match against multiple patterns using the | operator:

Python
x = 2

match x:
    case 1 | 2:
        print("x is 1 or 2")
    case _:
        print("x is neither 1 nor 2")

Output:

x is 1 or 2

Step 7: Using Nested match Statements

You can use nested match statements for more complex pattern matching:

Python
shape = ("rectangle", 2, 4)

match shape:
    case ("square", side_length):
        print(f"A square with side length {side_length}")
    case ("rectangle", x, y):
        match (x, y):
            case (a, a):
                print(f"A square disguised as a rectangle with side {a}")
            case (l, w):
                print(f"A rectangle with dimensions {l}x{w}")
    case _:
        print("Unknown shape")

Output:

A rectangle with dimensions 2x4

Step 8: Using Guards

You can add conditions using if:

Python
x = 5

match x:
    case n if n < 5:
        print("x is less than 5")
    case n if n == 5:
        print("x is exactly 5")
    case _:
        print("x is greater than 5")

Output:

x is exactly 5

Step 9: Advanced Data Matching

You can also match against custom classes using the __match_args__ attribute:

Python
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    __match_args__ = ("x", "y")

p = Point(2, 3)

match p:
    case Point(0, 0):
        print("Origin")
    case Point(x, y):
        print(f"Point at ({x}, {y})")
    case _:
        print("Not a point")

Output:

Point at (2, 3)

I hope this step-by-step tutorial helps you understand how to use match statements in Python. It’s a versatile feature that can simplify complex conditional logic.