Skip to content
beginner

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,…

Published 2026-09-05Updated 2026-09-127 min read
A student concentrating on writing during a class session in a warmly lit university classroom.
A student concentrating on writing during a class session in a warmly lit university classroom. Photo by Eduard Perez on Pexels.

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.

If more than one case could match a value, which case does Python run?
Single Choice

Focus: Explain how Python selects a case when multiple patterns could match.

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.

Which situation is presented as a good fit for match-case?
Single Choice

Focus: Choose between match-case and if-elif-else based on the kind of decision being expressed.

The Core Idea: Literals Compare, Names Capture

A flowchart starts with an input value, checks case patterns from top to bottom, and follows the first matching branch. It shows a literal such as 200 comparing for equality, a list pattern such as ["get", item] matching a two-item shape and capturing the second item, and an underscore wildcard handling unmatched values.
Pattern matching combines ordered case selection with value comparison, structure checking, and value 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 200 checks whether the value equals 200.
  • Names capture. A pattern like case item doesn't compare against an existing variable. It binds whatever value it sees to a new variable named item.
  • 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.

What does a bare name such as item in a pattern generally do?
Misconception Check

Focus: Distinguish a literal comparison pattern from a bare-name capture pattern.

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.

What does this program print?
Output Prediction

Focus: Predict the output produced when a list pattern captures one element.

command = "go north"
parts = command.split()

match parts:
    case ["go", direction]:
        print(f"Going {direction}...")
    case _:
        print("Other")

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.

What does ["get", item] require and provide when matching a command list?
Question 1 of 2Single Choice

Focus: Identify what a list pattern checks and captures when parsing command input.

In the article's example, why does case expected not test whether status equals the earlier value of expected?
Question 2 of 2Misconception Check

Focus: Recognize why a bare variable name does not compare against that variable's prior value in a case pattern.

References

  1. PEP 636 – Structural Pattern Matching: Tutorial | peps.python.orgpeps.python.org
8sources checked
8source domains
5searches run

Research updated Sep 5, 2026

Practical resource

Want a more structured Python path?

Use the Python Starter Pack to turn scattered tutorials into a focused practice path.

View the bundle
Coming soon

Python Starter Pack

A compact LearnPyFast PDF pack covering what Python is, installation, your first program, running Python code, and Python versions.

$9
PDF BundleTopic PackPythonBeginner
  • 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

Free Python bundle

Get the LearnPyFast Python Starter Bundle

A focused collection of beginner-friendly Python resources to help you move from setup to building practical projects.

You’ll receive the bundle by email. You can unsubscribe anytime.

No spam. You can unsubscribe anytime. See our Privacy policy.

Related sites

Continue beyond Python

Explore related Worldmonger sites when you want to move from Python basics into JavaScript or LLM application building.

JavaScript tutorialstutorial

LearnJSFast

Beginner-friendly JavaScript tutorials for practical web development and self-taught developers.

JavaScriptFrontendWeb development
Visit LearnJSFast
LLM tutorialstutorial

LearnLLMFast

Practical LLM tutorials for builders who want to understand prompting, workflows, agents, and AI applications.

LLMAIBuilders
Visit LearnLLMFast

Keep learning

Related tutorials

Continue with nearby Python topics and beginner-friendly explanations.

High-tech laboratory equipment with computer system in lab setting.
beginner
7 min read

For Loops in Python

A for loop is how Python repeats an action for every item in a collection. You describe the action once, and Python runs it for each value in turn. That…

Read tutorial
Two programmers working together with focus on coding in a modern, tech-savvy office environment.
beginner
8 min read

If Statements in Python

An if statement is how a Python program turns a condition into a decision: check something, then run one block of code or skip it. The whole skill is…

Read tutorial