Pattern Matching in Python: An Introduction to match-case
You know that feeling when you write a decision chain that keeps asking the same question about the same value? if status == 200, then elif status == 404,…

Key topics
You know that feeling when you write a decision chain that keeps asking the same question about the same value? if status == 200, then elif status == 404, then elif status == 500—each line repeating the comparison, each branch adding noise. Python's match-case statement cleans that up. It lets you compare one value against several patterns and run the code for the first one that matches.
But here's the part that makes it worth learning: match-case doesn't just compare values. It can look at the shape of your data and pull values out as it matches. That's the real reason to add it to your toolkit.
What Is match-case and Why Does It Exist?
Think of match-case as a modern cousin of the if-elif-else chain you already know. Instead of writing a long series of conditions, you write one match statement followed by several case blocks. Python looks at your value, checks it against each case from top to bottom, and runs the first one that matches.
This feature was added in Python 3.10, so before you try any of the examples in this article, make sure your Python version supports it:
python --version
If you see Python 3.10 or higher, you're ready to go. If you see something older, you'll need to upgrade before match-case will work.
Your First match-case: A Tiny Runnable Example
Let's look at the full shape of a match-case statement. Here's a small program that responds to simple text commands:
command = "start"
match command:
case "start":
print("Starting the program...")
case "stop":
print("Stopping the program...")
case "pause":
print("Pausing the program...")
case _:
print(f"Unknown command: {command}")
Run this and you'll see:
Starting the program...
Notice the underscore (_) in the last case. That's the wildcard pattern—Python's way of saying "if nothing else matched, do this." It works like the else at the end of an if chain. For user input, it's a good habit to include one, because you never know what value might show up. Just keep it last, since Python stops at the first matching case.
Try changing command to "stop" or "jump" and run it again. Watch which case runs each time.
Knowledge check
Check your understanding
Answer this question before you continue.
How match-case Compares to if-elif-else
Here's the same logic written two ways. First, the familiar if-elif-else version:
status = 404
if status == 200:
print("OK")
elif status == 404:
print("Not Found")
elif status == 500:
print("Internal Server Error")
else:
print("Unknown status")
Now the match-case version:
status = 404
match status:
case 200:
print("OK")
case 404:
print("Not Found")
case 500:
print("Internal Server Error")
case _:
print("Unknown status")
Both produce the same output:
Not Found
So when should you use which? My rule is simple: match-case shines when you're checking one value against many distinct possibilities. The code reads more like a menu than a list of questions.
But if-elif-else stays useful when your conditions are complex—when you're combining multiple variables, using comparison operators like < or >, or mixing in logical operators like and and or. match-case is for matching values, not for evaluating complicated expressions.
Knowledge check
Check your understanding
Answer this question before you continue.
The Core Idea: Literals Compare, Names Capture
Before we go further, you need one rule that explains most of what confuses beginners about match-case:
- Literals compare. A pattern like
case 200checks whether the value equals200. - Names capture. A pattern like
case itemdoesn't compare against an existing variable. It binds whatever value it sees to a new variable nameditem. - Structure describes shape. A pattern like
["get", item]checks that the data is a two-element list whose first element is"get", and captures the second element.
Keep that rule in mind. It will save you from the most common match-case mistake, which we'll get to shortly.
Knowledge check
Check your understanding
Answer this question before you continue.
Matching More Than Literals: Patterns in Action
Here's where match-case becomes more than just a cleaner switch statement. The patterns you match against can check the shape of your data, not just exact values.
Imagine you're writing a text adventure game. Players type commands like "go north" or "get key". You can split the command into words and match against the resulting list:
command = "get key"
parts = command.split()
match parts:
case ["quit"]:
print("Goodbye!")
case ["go", direction]:
print(f"Going {direction}...")
case ["get", item]:
print(f"Picking up the {item}...")
case _:
print(f"I don't understand: {command}")
This prints:
Picking up the key...
See what happened? The pattern ["get", item] matched a two-element list whose first element was "get". And it did something clever: it captured the second element into a variable called item. Now you can use that variable inside the case block.
Notice that the pattern also enforces the length. ["get", item] only matches a list with exactly two elements. If the player types "get" alone, that case won't match—Python will move on to the next one.
Let's prove the capture works by trying another command:
command = "go north"
parts = command.split()
match parts:
case ["quit"]:
print("Goodbye!")
case ["go", direction]:
print(f"Going {direction}...")
case ["get", item]:
print(f"Picking up the {item}...")
case _:
print(f"I don't understand: {command}")
This prints:
Going north...
The pattern ["go", direction] matched the two-element list ["go", "north"] and captured "north" into direction. Same structure, different captured value.
That's the real power of pattern matching. It's not just checking values—it's pulling values out of structures as it matches. A case pattern can describe the structure of data, not just a single value.
Knowledge check
Check your understanding
Answer this question before you continue.
Common Beginner Mistakes
Every Python feature has its traps, and match-case is no exception. Here are the mistakes I see beginners make most often.
Using an older Python version. If you're on Python 3.9 or earlier, match and case will raise a syntax error. The fix is simple: upgrade to Python 3.10 or later.
Using a bare variable name when you mean to compare against a value. This one surprises everyone, and it follows directly from the rule above. Look at this code:
expected = 200
match status:
case expected:
print("Matched!")
You might expect this to check if status == expected. It doesn't. Because expected is a bare name, it acts as a capture pattern—it matches anything and assigns the value of status to expected. The case will always run, no matter what status is.
To compare against a variable's value, you need a dotted name, like case config.expected:. The dot tells Python you mean an existing value, not a new capture.
Forgetting that only the first match runs. Python checks cases from top to bottom and stops at the first one that matches. If you have overlapping patterns, order matters. Put more specific patterns first and the wildcard _ last.
Where You'll Meet Pattern Matching in Real Code
match-case isn't just a classroom curiosity. You'll see it in real Python codebases, especially in command-line tools, menu systems, and programs that handle different types of user input or API responses.
Think about an automation script that reads commands from a file or a chat bot that parses user messages. In both cases, you're doing the same thing as the text adventure example: taking a piece of input, checking its structure, and deciding what action to take. Pattern matching gives you a clean way to express that decision.
A common real-world example is handling HTTP status codes, like the examples above. Another is parsing commands in chat bots or automation scripts. Once you start looking for it, you'll notice the pattern: one value, several possible shapes, each shape leading to a different action.
Your Next Step
The best way to make this stick is to use it. Go back to an earlier program you wrote with a long if-elif-else chain—something that checks one value against several possibilities. Rewrite it as a match-case statement and run it. Compare the two versions side by side. Notice how the match-case version reads.
Then push yourself one step further. Write a small command parser that handles both "go north" and "get key" style inputs, using patterns to capture the details. That exercise will force you to practice the part of match-case that makes it special: matching structure and pulling values out at the same time.
Knowledge check
Final check
Finish the article by checking the ideas you just learned.
References
Research updated Sep 5, 2026
Want a more structured Python path?
Use the Python Starter Pack to turn scattered tutorials into a focused practice path.
Python Starter Pack
A compact LearnPyFast PDF pack covering what Python is, installation, your first program, running Python code, and Python versions.
- 5 curated chapters
- Enhanced PDF edition with bundle-only learning guidance
- Offline-friendly format for focused review
- Source article links for future online updates
Coming soon


