Using Match Case For Pattern Matching In Python

Using Match Case For Pattern Matching In Python

Sachin Pal's photo
Sachin Pal
·Feb 17, 2023·

9 min read

Play this article

Table of contents

  • If-Else Statement
  • Match Case Statement
  • Conclusion

Python programming language is constantly evolving and every new version of it brings something interesting and new. In Python version 3.10, the "match case" statement was proposed in the PEP 634(specification) & 636(tutorial) for structural pattern matching.

Just like other programming languages like C, Java, JavaScript and more has a switch statement that provides a way to perform conditional operations based on the values of an expression. The switch statement allows us to execute the block of code based on the value of the single expression.

But Python didn't have that amenity from the start instead of an if-else statement, so in the recent version of Python, the match case statement was introduced that functions similarly to the switch statement.

If-Else Statement

Before the proposal or release of the match case statement in Python, the if-else statement is primarily used for pattern matching or performing conditional operations.

Here's an example of using the if-else statement to perform the conditional operation.

user = input("Enter the number: ")

if int(user) > 10:
    print("Greater than 10")

elif int(user) < 10:
    print("Less than 10")

    print("It's sleeping time.")

In the above code, we specified some conditions and which condition will be going to be true depends on the value of the single expression which the user in the console will enter.

Here, if the user inputs a value greater than 10 then the first condition will be going to be true and the program terminates but if the value is less than 10, the program will check the first condition if that's not true then it will move onto the following condition, if it found the match then it will execute the condition and terminates there.

Enter the number: 10
It's sleeping time.
Enter the number: 9
Less than 10
Enter the number: 11
Greater than 10

The program will always look for a match and in the end, will execute the condition that matches the user's requirement.

Match Case Statement

The newly added match case statement functions similarly to the if-else statement and if you have worked with other programming languages like C, JavaScript and more, then it'll give you the feel like the switch statement.

The match statement takes an expression and compares its value with the case blocks which have some specified conditions. Take a look at the following example showing the simplest demonstration of the match statement.

greet = "Hey"

match greet:
    case "Hey":
        print("Welcome to GeekPython.")
    case "Hello":
        print("Welcome Geeks.")
    case _:
        print("Matches anything.")

In the above code, we created a variable greet in which a value "Hey" is stored and then we created the match case block. First, we wrote the match keyword and specified the parameter then we defined the case blocks where we wrote the conditions and whichever condition will be true gets executed.

Welcome to GeekPython.

In the last case block, we defined case _, where the variable name _ acts as a wildcard and it will never fail to match. If no case matches in the upper code then the last case block is executed.

In the sections ahead, you'll discover many other concepts in the match statement.


The guard in the match statement is nothing but using if statement in the case block. It is a part of the case block and the syntax is:

case case_here if named_expression

The idea behind the guard or using the if statement in the case block is when the condition is matched with the case, the program will not execute it right away it then moves on to the guard condition or if condition and if the if condition is true, then the block is executed else it will not be executed.

Another logical flow of the case with the guard is if the case doesn't match then the guard will not be evaluated and the program moves to the next case block.

num = 10
match ("Hey", 1):
    case ("Hello", 10):
        print("Case 1 matched")
    case ("Hey", 1) if num == 1: # Case matched but guard fails
        print("Case 2 matched")
    case ("Hey", n):
        print(f"Case 3 matched, n={n}")
    case _:
        print("Match anything")

If we look at the second case block that matches the condition that we defined in the match condition and after that program evaluates the guard but here, the guard condition is false, hence the program moves on to the next case block.

In the third case block, it matches the condition and binds the n with the value 1 and the program executes the third case block.

Case 3 matched, n=1

Using OR Pattern

Pattern matching will not always be about matching a single condition, sometimes we might want to match either this or that condition and in that case, we can use the | (pipe) character in the case block to specify alternative patterns.

match ("Hey", 1):
    case ("Hello", 10):
        print("Case 1 matched")
    case ("Hey", 10) | ("Heya", 1) | ("Hey", 1):
        print("Case 2 matched")
    case _:
        print("Match anything")

Here's a simple demonstration of using the or pattern where in the second case block, three conditions were defined and if either one of them matches the condition the program is looking for, the case block will get executed.

Case 2 matched

Matching a Sequence

Sometimes we might want to create or define the specific program or function in which we wanted to match certain sequences from the dynamic or static data.

Then at that time, we can use sequence matching and there are several methods to perform it but we'll see how to do it in a match case statement.

letter = "Hello"

match (letter[4]):
    case "o":
        print("Case 1 matched")
    case "a":
        print("Case 2 matched")
    case _:

In the above code, we are trying to match the condition of whether a specific character is present in our given sequence or not. This code will look for a case where the specific character matches the condition and then the program will execute it.

Case 1 matched

One more thing is that if we wanted to match one certain character from the sequence and then the whole sequence collectively then, in that case, we could use * with the variable name. This will simply grab all the values present in the data or sequence.

def inputdata(data):
    match data:
        case ["Hello", *other]:
            print(f"First letter is 'Hello' and "
                  f"Others are {other}")
        case [*word, "Welcome"]:
            print(f"Last word is 'Welcome' and the words "
                  f"before is {word}")
        case _:

inputdata(["Hello", "Geeks"])
inputdata(["Hey", "Geeks", "Welcome"])

In the above code, the first case will match the word "Hello" from the given sequence and then match all the other items and the same goes for the second case block.

First letter is 'Hello' and Others are ['Geeks']
Last word is 'Welcome' and the words before is ['Hey', 'Geeks']

Python Class in Match Statement

We can also use Python classes for pattern matching using match case statements. This will help us manage our code easily, and the code will be easily readable in the case of a complex code structure.

from dataclasses import dataclass

class Hero:
    real_name: str
    reel_name: str
    hero_name: str

def class_in_match(data):
    match data:
        case Hero(real_name, reel_name, hero_name):
            print(f"{real_name} plays the character of {reel_name} and "
                  f"hero name is {hero_name}.")

        case Hero("Tobey Maguire", "Peter Parker", "SpiderMan"):
            print("Tobey Maguire plays the character of Peter Parker and "
                  "hero name is SpiderMan.")

obj1 = Hero("RDJ", "Tony Stark", "IronMan")
obj2 = Hero("Tobey Maguire", "Peter Parker", "SpiderMan")


In the above code, we used the dataclass and created our class Hero which has three arguments.

In the next code block, we created a function class_in_match that takes the data as an argument, then we started the match-case ladder where the condition is to match the data and in the first case block, we instantiated the class Hero and passed the required arguments. In the second case block, instead of passing arguments, we passed the values of the arguments.

Then we created the instance obj1 and obj2 for the class Hero and passed the values and then finally called the function class_in_match and passed the instance of the class.

RDJ plays the character of Tony Stark and hero name is IronMan.
Tobey Maguire plays the character of Peter Parker and hero name is SpiderMan.

For Loop with Match Case

Like we used to do in the traditional way where we run for loop and then specify conditions using the if-elif-else ladder to carry out the specific task. This time we'll see how to do it with the match-case statement.

seq = "GeekPython"

for i in seq:
    match i:
        case "y":
            print(f"The sequence has letter {i}")
        case "e":
            print(f"The sequence has letter {i}")
        case _:
            print(f"Other letter {i}")

The above code will run a for loop for every letter in the seq variable and tries to match i which is basically every letter in the seq, we created three case blocks, the first one matches if seq has the letter "y" in it, so does the second one but for the letter "e" and the third one matches the other letters.

Other letter G
The sequence has letter e
The sequence has letter e
Other letter k
Other letter P
The sequence has letter y
Other letter t
Other letter h
Other letter o
Other letter n

Match Case with Python Dictionary

Here we'll see how we can create the match-case statement using the Python dictionary. This can be very helpful when your project is on the cloud and the communication of the data needs to be in the json format or dictionary.

data = {
    "name": "GeekPython",
    "role": "Developer",
    "type": "Python"

match data["name"][4:]:
    case "GeekPython":
        print("Case 1 matched")
    case "Python":
        print("Case 2 matched")
    case "python":
        print("Case 3 matched")
    case _:

In the above code, the variable data is a dictionary and contains some key-value pairs and then we created the condition to match the value of the key name from the dictionary data. We created some case blocks and whichever case fulfils the required condition will get executed.

The condition is to match the value of the key name starting from the index number 4 and the second case perfectly matches the specified condition.

 Case 2 matched


The match-case statement was added in Python v3.10 and in the first look, it gives the feeling of using switch statements like in other programming languages. Sure, Python has an if-else statement but adding a match-case statement in Python comes with a great plus point.

In this article, we've seen the usage of the match-case statement and along with it understood some important concepts of the match-case statement with code examples.

The match-case statement functions similarly to the if-else statement and the syntax is also similar to some extent.

🏆Other articles you might like if you like this article

Using underscores to control the behaviour of the methods in the Python class.

Class Inheritance in Python and types of inheritance.

Build Web APIs in just a few steps using FastAPI.

Upload and display images on the frontend using Flask.

An intuitive guide to data augmentation in deep learning using Python.

Implement a deep learning model in the Flask app for image recognition.

That's all for now

Keep Coding✌✌

Did you find this article valuable?

Support Sachin Pal by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
Share this