Python is a versatile programming language, it introduced the match statement in version 3.10. It is very similar to the switch-cases that many other programming languages like C, C++, or Java have. This feature allows for more expressive and readable code when dealing with complex data structures. In this blog, we will explore what the match statement is, why it is used, its features, and common mistakes that students often make when learning it.
Table of Contents
What is the Match Statement?
The Match Case statement is Python’s new way of making decisions based on different choices, similar to the traditional switch-case statement in other languages. It allows you to compare a given variable’s value to different patterns or cases or options and execute the block of code of that option or case or matched pattern.
Let’s take an example where you want to match a variable’s value:
If the value is 10, perform a specific action.
If the value is 20, perform another action.
If the value is neither 10 nor 20, do a default action for anything else.
Syntax:
match variable:
case pattern1:
# Code to execute if pattern1 matches
case pattern2:
# Code to execute if pattern2 matches
case _:
# Default case (similar to else)
PythonHere, _
is used for default case. If none of the cases or option match this code of block will execute.
For Example:
x = int(input("Enter a number: "))
match x:
case 10:
print("Ten")
case 20:
print("Twenty")
case _:
print("Something else")
# Output:
# Enter a number: 10
# Ten
# Enter a number: 20
# Twenty
# Enter a number: 30
# Something else
PythonWhy and How is it Used?
The match statement is also used for more complex matching scenarios, such as matching against data structures like lists and dictionaries even Graphs. It makes code more cleaner and maintainable, because it reduces the need for multiple if-elif-else
statements, leading to cleaner and more maintainable code.
Example with tuple
point = (2, 3)
match point:
case (0, 0):
print("Origin")
case (x, 0):
print(f"On the X-axis at {x}")
case (0, y):
print(f"On the Y-axis at {y}")
case (x, y):
print(f"Point at ({x}, {y})")
PythonCase 1: (0, 0)
case (0, 0):
print("Origin")
Python- This checks if
point == (0, 0)
. - Since
point
is(2, 3)
, this condition does not match.
Case 2: (x, 0)
case (x, 0):
print(f"On the X-axis at {x}")
Python- This pattern checks if
point
has the form(x, 0)
, meaning the second value must be0
. point = (2, 3)
, but3 ≠ 0
, so this does not match.
Case 3: (0, y)
case (0, y):
print(f"On the Y-axis at {y}")
Python- This pattern checks if
point
has the form(0, y)
, meaning the first value must be0
. point = (2, 3)
, but2 ≠ 0
, so this does not match.
Case 4: (x, y)
(General Case)
case (x, y):
print(f"Point at ({x}, {y})")
Python- This pattern matches any tuple with two values.
point = (2, 3)
, sox = 2
andy = 3
are assigned automatically.- This case matches, so Python prints:
Point at (2, 3)
When Python finds a match in a case (x, y):
pattern:
- It extracts values from
point = (2, 3)
. - Assigns
x = 2
andy = 3
. - Executes the corresponding block.
This is called pattern unpacking, which allows the variables (x, y
) to be initialized only when the pattern matches.
Example with dictionary
This pattern unpacking or variable assignment is very usefull actually. This example will show you why.
user = {"name": "Alice", "age": 25}
match user:
case {"name": name, "age": age} if age >= 18:
print(f"{name} is an adult")
case {"name": name, "age": age}:
print(f"{name} is a minor")
case _:
print("Invalid data")
PythonCase 1
case {"name": name, "age": age} if age >= 18:
print(f"{name} is an adult")
Python- This pattern matches any dictionary that has:
- A
"name"
key (the value Alice is assigned toname
). - An
"age"
key (value is assigned toage
).
- A
- Condition:
if age >= 18
age = 25
, which satisfies the condition.- So, it matches and executes:
print(f"{name} is an adult") # Output: Alice is an adult
Case 2:
case {"name": name, "age": age}:
print(f"{name} is a minor")
Python- This would match any dictionary with key
"name"
and"age"
.
Pattern Matching with Conditions (if age >= 18
)
- This case binds
name
andage
from the dictionary. - The
if
condition ensuring the match happens only if the condition is true.
Benefits Over if-else
Feature | match case | if-else |
---|---|---|
Pattern Matching | Can directly extract and assign values from a dictionary. | Needs explicit dictionary access (user["name"] , user["age"] ). |
Readability | Cleaner and structured. | Can become long and repetitive. |
Multiple Cases | Allows multiple structured matches in one block. | Requires multiple if-elif blocks. |
Performance | Faster for multiple patterns (optimized internally). | Checks conditions sequentially, may be slower. |
Would This Work with if-else
?
Yes! But it would be less elegant:
user = {"name": "Alice", "age": 25}
if "name" in user and "age" in user:
name = user["name"]
age = user["age"]
if age >= 18:
print(f"{name} is an adult")
else:
print(f"{name} is a minor")
PythonThis is more verbose and manually extracts values.
Conclusion
In conclusion, the match statement in Python is a powerful tool that makes coding easier and cleaner. It helps you compare values and execute specific actions based on those values without using many if-else statements. This feature is especially useful for working with complex data like lists and dictionaries. By using match statements, your code becomes more organized and easier to read. So, practice with match statements as it can really help you improve your programming skills.