In this tutorial, we’ll explain multiple ways to implement the Match Case In Python
. Before we get started, if you want to Conditional Statements in Python, please go through the following article: Conditional Statements in Python.
Introduced in Python 3.10, the match case statement offers a powerful mechanism for pattern matching in Python. It allows us to perform more expressive and readable conditional checks. Unlike traditional if-elif-else chains, which can become unwieldy with complex conditions, the match case statement provides a more elegant and flexible solution.
Basic Match Case
1 2 3 4 5 6 7 8 9 |
value = "apple" match value: case "apple": print("It's an apple!") case "banana": print("It's a banana!") case _: print("Unknown fruit") |
This checks the value of value
and prints a specific message based on the match. The underscore _
is a wildcard pattern that matches anything (like “else”).
Match with If Conditions (Guards)
1 2 3 4 5 6 7 8 9 |
num = 10 match num: case n if n < 0: print("Negative number") case n if n == 0: print("Zero") case n if n > 0: print("Positive number") |
Each case uses a guard condition (if
) to check for additional logic beyond the pattern. Here, the value is categorized based on its sign.
Using OR (|) in Patterns
1 2 3 4 5 6 7 8 9 |
color = "red" match color: case "red" | "blue": print("Primary color") case "green": print("Secondary color") case _: print("Unknown color") |
The |
operator allows matching multiple values in one case. If color
is either “red” or “blue”, it prints “Primary color”.
Matching Multiple Conditions with Tuples
1 2 3 4 5 6 7 8 9 10 11 |
point = (0, 0) match point: case (0, 0): print("Origin") case (x, 0): print(f"X-axis at {x}") case (0, y): print(f"Y-axis at {y}") case (x, y): print(f"Point at ({x}, {y})") |
Tuple destructuring is used to match coordinate points. You can match exact values or capture variables for later use, as seen with x
and y
.
Matching Values with Patterns
1 2 3 4 5 6 7 8 9 |
user = ("John", "Admin") match user: case ("John", role): print(f"John's role is {role}") case (_, "User"): print("Generic user") case _: print("Unknown user") |
This pattern extracts values from a tuple and uses _
to ignore parts. In the first case, if the first value is “John”, the second part is captured as role
.
Match Case on Sequences
1 2 3 4 5 6 7 8 9 10 11 |
items = ["apple", "banana"] match items: case []: print("Empty list") case [first]: print(f"One item: {first}") case [first, second]: print(f"Two items: {first}, {second}") case [first, *rest]: print(f"First: {first}, Rest: {rest}") |
This demonstrates pattern matching on list structures. It detects the list size and captures elements using destructuring. The *rest
syntax captures remaining items.
Match Case on Dictionaries (Mappings)
1 2 3 4 5 6 7 8 9 |
person = {"name": "Alice", "age": 30} match person: case {"name": "Alice", "age": age}: print(f"Alice is {age} years old.") case {"name": name}: print(f"Name found: {name}") case _: print("No match") |
This shows how dictionaries (mappings) can be pattern-matched by checking for specific keys. Values can be extracted and assigned to variables directly in the pattern.
Match Case with Python Classes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Animal: def __init__(self, name): self.name = name class Dog(Animal): def __init__(self, name, breed): super().__init__(name) self.breed = breed class Cat(Animal): pass pet = Dog("Max", "Labrador") match pet: case Dog(name="Max", breed="Labrador"): print("Max the Labrador!") case Cat(name=name): print(f"A cat named {name}") case _: print("Unknown pet") |
Python can match against class instances by checking their type and fields (if they follow the right signature or are dataclass
-like). This example matches different subclasses of Animal
and extracts fields.
Benefits of Match Case
- Improved readability over long
if-elif
chains - Pattern matching on sequences, dictionaries, and classes
- Supports guards, wildcards, and OR conditions
- Clean handling of complex branching logic
Conclusion
Python’s match case
brings powerful structural pattern matching to the language, making conditional logic more elegant and less error-prone. It’s particularly useful when working with complex data structures, parsing inputs, or handling different types of objects and responses.
It’s a feature worth learning and applying in modern Python codebases, especially for those coming from languages like Scala, Haskell, or Rust where pattern matching is idiomatic.
Leave a Comment