- Courses
- 💻Programming Languages
- 🐍Python
- Control Flow
- Match/Case Statements
On this page
Python Match Statement: Guide to Modern Control Flow
Published on July 6, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
The match statement, introduced in Python 3.10, is a powerful tool for controlling the flow of your program. Think of it as a supercharged version of a chain of if/elif/else statements, designed for clarity and expressiveness. It allows you to check a value against a series of patterns and execute code based on which pattern matches. This is Python's answer to the switch or case statements found in other programming languages like C++, Java, or JavaScript. However, the match statement goes far beyond simple value comparison; it can inspect the structure of your data, making it an incredibly useful tool for writing clean and robust code.
The Problem: Long Chains of if/elif/else
Before Python 3.10, handling multiple conditions often meant writing long chains of if/elif/else statements. While this works, it can become repetitive, difficult to read, and prone to errors as the number of conditions grows.
Here is a classic example: handling HTTP status codes.
# The "Old" Way: A long if-elif-else chain
status_code = 404
if status_code == 200:
print("Success!")
elif status_code == 404:
print("Not Found")
elif status_code == 500:
print("Internal Server Error")
else:
print("Unknown status code")
This works, but it's verbose. You have to repeat status_code == for every condition, which clutters the code and makes it harder to scan.
The Solution: The match Statement
The match statement solves this problem by providing a much cleaner and more streamlined way to write this same logic.
Basic Syntax
The basic syntax of the match statement is straightforward:
match expression:
case pattern_1:
# action_1
case pattern_2:
# action_2
case _:
# default action
Here is how it works:
match expression: Thematchkeyword is followed by the value you want to check. This is called the subject.case pattern: Thecasekeyword is followed by a pattern to compare against the subject. If the pattern matches, the indented code block below it is executed.case _:: The underscore (_) is a special wildcard pattern that acts as a default or catch-all. It matches anything and is similar to theelseblock in anif-elsestatement. Once a match is found, the corresponding block runs, and the rest are skipped. There is no "fall-through" like in some other languages'switchstatements.
match vs if-elif-else: A Side-by-Side Comparison
Let's rewrite the HTTP status code example using the match statement:
# The "New" Way: Using the match statement
status_code = 404
match status_code:
case 200:
print("Success!")
case 404:
print("Not Found")
case 500:
print("Internal Server Error")
case _:
print("Unknown status code")
The code is immediately easier to read and scan. The logic is organised clearly, and the structure of the pattern matching is more intuitive.
Beyond Simple Values: Matching Structures
The real power of the match statement lies in its ability to match patterns, not just literal values. A pattern can describe the structure of the data you expect. This makes it incredibly useful for handling complex data like lists, tuples, and dictionaries.
Example: Matching Against a List
Imagine you are writing a function that processes different kinds of commands, some of which have arguments.
def process_command(command):
match command:
case ["quit"]:
print("Exiting program.")
case ["save", filename]:
print(f"Saving file to: {filename}")
case ["load", filename]:
print(f"Loading file from: {filename}")
case ["help"]:
print("Showing help.")
case _:
print(f"Unknown command: {command}")
# Test the function
process_command(["save", "my_document.txt"]) # Output: Saving file to: my_document.txt
process_command(["quit"]) # Output: Exiting program.
process_command(["hello"]) # Output: Unknown command: ['hello']
Let's break down what is happening:
case ["quit"]:: This pattern matches a list with exactly one element, which is the string"quit".case ["save", filename]:: This pattern matches a list with exactly two elements. The first must be the string"save". The second element is captured into a variable calledfilename. This is called a capture pattern.case ["load", filename]:: This works similarly to the["save", filename]pattern.case _:: This is the wildcard pattern that matches any command that doesn't fit the other patterns.
This declarative style makes the code's intent very clear: you are checking the structure of a list and capturing its parts at the same time.
Pattern Types
The match statement supports several different kinds of patterns, making it incredibly flexible.
1. Literal Patterns
These match exact values like numbers, strings, booleans, and None.
def describe_value(value):
match value:
case 0:
return "Zero"
case 42:
return "The answer to life, the universe, and everything"
case "hello":
return "Greeting"
case True:
return "Boolean True"
case None:
return "Nothing"
case _:
return f"Something else: {value}"
2. OR Patterns
You can match multiple patterns in a single case using the pipe (|) operator. This is perfect for handling multiple values that should trigger the same code block.
def classify_status(status_code):
match status_code:
case 200 | 201 | 202:
return "Success"
case 400 | 401 | 403 | 404:
return "Client Error"
case 500 | 501 | 502:
return "Server Error"
case _:
return "Unknown Status"
3. Wildcard Pattern
The underscore (_) is the wildcard pattern. It acts as a catch-all for any value that hasn't been matched by previous case statements. It is always a good idea to include a wildcard case at the end of your match statement to handle unexpected values gracefully. If you don't, and no pattern matches, your program might encounter an error or do nothing silently.
Adding Conditions with Guards
Sometimes, you need to match a pattern only if an additional condition is true. This is where guards come in. A guard is an if condition that follows a pattern.
def process_number(x):
match x:
case 0:
print("It's zero.")
case x if x > 0: # Guard: only matches if x is greater than 0
print(f"It's a positive number: {x}")
case x if x < 0: # Guard: only matches if x is less than 0
print(f"It's a negative number: {x}")
case _:
print("Not a number?")
In this example, case x if x > 0: matches any value of x (capturing it into the variable x), but only if the x > 0 condition is true.
When to Use match vs. if/elif/else
The match statement is not meant to replace if/elif/else entirely. It is a tool for specific situations.
-
Use the
matchstatement when:- You are checking a single value against many possible patterns.
- You need to inspect and destructure complex data types like lists, tuples, or dictionaries.
- You want to write highly readable and declarative code.
-
Use
if/elif/elsewhen:- You have complex conditions involving multiple variables or functions.
- You need to check for ranges of values (e.g.,
if 10 < x < 20). - You are working with older versions of Python (pre-3.10).
The match statement offers a more elegant and safer way to express multiple conditional branches, especially when working with structured data.
Common Mistakes to Avoid
1. Forgetting the Wildcard
Always include a case _: at the end. This prevents your program from doing nothing if no patterns match, which can be a difficult bug to track down.
2. Assuming Fall‑Through
Unlike switch in some languages, Python's match does not fall through to the next case. Once a match is found, the match block is exited. Do not try to use break or rely on fall‑through.
3. Using match with Python Versions Before 3.10
The match statement was introduced in Python 3.10. If you are using an older version of Python, you cannot use this feature. Use if/elif/else chains instead.
Summary
The match statement is a powerful and expressive addition to Python that elevates how you handle conditional logic. It allows you to write cleaner, more readable, and more maintainable code compared to long if/elif/else chains. By understanding its syntax and the different types of patterns it supports, you can write code that is not only easier to read but also safer and less error-prone.
The match statement is not just a simple switch; it's a form of structural pattern matching that lets you peer into the structure of your data, making it a powerful tool for everything from command processing to complex data validation. Embrace this feature to make your Python code more modern and Pythonic.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
If/Else Statements
Next
For Loops
-
The Problem: Long Chains of
if/elif/else -
The Solution: The
matchStatement- Basic Syntax
matchvsif-elif-else: A Side-by-Side Comparison
-
Beyond Simple Values: Matching Structures
- Example: Matching Against a List
-
Pattern Types
- 1. Literal Patterns
- 2. OR Patterns
- 3. Wildcard Pattern
-
Adding Conditions with Guards
-
When to Use
matchvs.if/elif/else -
Common Mistakes to Avoid
- 1. Forgetting the Wildcard
- 2. Assuming Fall‑Through
- 3. Using
matchwith Python Versions Before 3.10
-
Summary
