Module 3 · Beginner · Conditions and loops

Python match statement, with examples

The Python match statement (match case) with examples: matching values, several options with |, the _ wildcard, guards, and matching lists and dictionaries.

By theprogrammers team · · 8 min read

A food-delivery app gets an order status: "placed", "cooking", "out for delivery", "delivered" or "cancelled". For each one it shows a different message. You could write a long chain of if, elif, elif, but Python 3.10 added a neater way: the Python match statement, also called match case or structural pattern matching.

match compares one value against a list of patterns and runs the code for the first one that fits. For simple choices it reads like a menu. It can also look inside lists and dictionaries and pull out the parts you need, which if can't do as neatly.

What you need first: Python if, elif and else and Python lists.

Key terms

  • Subject: the value after match, the thing being checked.
  • Pattern: what comes after case. It describes the shape or value the subject must have.
  • Wildcard _: a pattern that matches anything. It's used as the "everything else" case.
  • Guard: an extra if condition on a case, like case x if x > 100.
  • Capture: a pattern can store part of the subject in a new variable for you to use.

Check your Python version

match only works in Python 3.10 or newer (released in October 2021). On older versions you get a SyntaxError. Check yours with:

import sys
print(sys.version_info >= (3, 10))
True

If it prints False, see how to install Python to get a newer version.

The basic match case syntax

status = "cooking"

match status:
    case "placed":
        print("We've got your order.")
    case "cooking":
        print("The restaurant is preparing your food.")
    case "delivered":
        print("Enjoy your meal.")
    case _:
        print("Status unknown.")
The restaurant is preparing your food.

Python checks each case from top to bottom. The first one that matches runs, and then the whole match ends. Unlike switch in C or Java, there's no "fall through" to the next case and no break needed.

case _: is the default. It matches anything, so put it last. If no case matches and there's no _, nothing happens and no error is raised.

Several values in one case

Use | (read "or") to give one case several values:

def day_type(day):
    match day.lower():
        case "saturday" | "sunday":
            return "Weekend"
        case "monday" | "tuesday" | "wednesday" | "thursday" | "friday":
            return "Weekday"
        case _:
            return "Not a day"

print(day_type("Sunday"))
print(day_type("wednesday"))
print(day_type("Funday"))
Weekend
Weekday
Not a day

match vs if-elif

Here's the same logic written both ways, for HTTP status codes (the numbers a website sends back, like 404 for "not found"):

def describe(code):
    match code:
        case 200:
            return "OK"
        case 404:
            return "Not found"
        case 500 | 502 | 503:
            return "Server error"
        case _:
            return "Something else"

def describe_if(code):
    if code == 200:
        return "OK"
    elif code == 404:
        return "Not found"
    elif code in (500, 502, 503):
        return "Server error"
    else:
        return "Something else"

for code in [200, 404, 502, 301]:
    print(code, describe(code), describe_if(code))
200 OK OK
404 Not found Not found
502 Server error Server error
301 Something else Something else

For a handful of fixed values, both are fine. Our advice: use if for ranges and conditions (marks above 90, age under 18) and use match when you're checking one value against fixed options, or the shape of a list or dictionary. That's where match is clearly better.

Guards: adding a condition

A plain pattern can't say "greater than 90". Add a guard with if. The name marks here is a capture: it matches anything and stores the value so the guard can test it.

def grade(marks):
    match marks:
        case marks if marks >= 90:
            return "A"
        case marks if marks >= 75:
            return "B"
        case marks if marks >= 40:
            return "C"
        case _:
            return "Fail"

for m in [95, 80, 52, 30]:
    print(m, grade(m))
95 A
80 B
52 C
30 Fail

This works, but it's honestly no clearer than if/elif. Grades are a range problem, so if is the better tool here. Guards are most useful together with the list and dictionary patterns below.

Matching lists: commands with parts

This is where match shines. Say a chatbot reads commands like "add milk 2" or "remove bread". After split(), each command is a list, and match can check its length and pull out the parts in one step:

def run(command):
    match command.split():
        case ["add", item, qty]:
            return f"Adding {qty} x {item}"
        case ["add", item]:
            return f"Adding 1 x {item}"
        case ["remove", item]:
            return f"Removing {item}"
        case ["list"]:
            return "Showing your cart"
        case []:
            return "You didn't type anything"
        case _:
            return "Unknown command"

for c in ["add milk 2", "add bread", "remove milk", "list", "", "dance"]:
    print(run(c))
Adding 2 x milk
Adding 1 x bread
Removing milk
Showing your cart
You didn't type anything
Unknown command

case ["add", item, qty] means "a list of exactly three items, the first being "add"". The other two are captured into item and qty. Doing this with if needs a length check and indexing for every case.

To match "any number of extra items", use *rest:

match ["send", "Ahana", "Rohan", "Meera"]:
    case ["send", *people]:
        print(f"Sending to {len(people)} people: {people}")
Sending to 3 people: ['Ahana', 'Rohan', 'Meera']

Matching dictionaries

Data from websites and APIs usually arrives as dictionaries. A dictionary pattern checks for certain keys and captures their values. Extra keys are allowed.

def handle(event):
    match event:
        case {"type": "payment", "amount": amount}:
            return f"Payment of ₹{amount}"
        case {"type": "refund", "amount": amount, "reason": reason}:
            return f"Refund of ₹{amount}: {reason}"
        case {"type": t}:
            return f"Ignoring event of type {t}"
        case _:
            return "Not an event"

print(handle({"type": "payment", "amount": 499, "upi": "ahana@okbank"}))
print(handle({"type": "refund", "amount": 120, "reason": "late delivery"}))
print(handle({"type": "login"}))
print(handle("hello"))
Payment of ₹499
Refund of ₹120: late delivery
Ignoring event of type login
Not an event

Common mistakes

Using a variable name to mean a value. This is the biggest trap. A bare name in a case is a capture, not a comparison:

wanted = "delivered"
status = "cooking"

match status:
    case wanted:
        print(f"Matched! wanted is now {wanted!r}")
Matched! wanted is now 'cooking'

case wanted: didn't compare with "delivered". It matched anything and overwrote wanted. To compare with a stored value, use a guard (case s if s == wanted:) or a dotted name such as a constant in a class or enum (case Status.DELIVERED:).

Other mistakes:

  • Putting case _: first. It matches everything, so later cases never run.
  • Running on Python 3.9 or older, which gives SyntaxError: invalid syntax.
  • Using match for ranges. Use if/elif for "between 40 and 75".

Practice

  1. Write vehicle_wheels(kind) that returns 2 for "bike" or "scooter", 3 for "auto", 4 for "car", and 0 for anything else.
Show the answer
def vehicle_wheels(kind):
    match kind:
        case "bike" | "scooter":
            return 2
        case "auto":
            return 3
        case "car":
            return 4
        case _:
            return 0

print(vehicle_wheels("auto"), vehicle_wheels("scooter"), vehicle_wheels("boat"))
3 2 0
  1. What does this print, and why?
match [1, 2]:
    case [x]:
        print("one item")
    case [x, y]:
        print("two items:", x + y)
    case _:
        print("other")
Show the answer
two items: 3

[x] needs exactly one item, so it fails. [x, y] matches a list of two, capturing 1 and 2.

  1. A calculator gets a list like [8, "+", 2]. Use match to handle +, -, * and /, and return "Can't divide by zero" when dividing by 0.
Show the answer

The divide-by-zero case must come before the normal divide case, because the first match wins:

def calc(expr):
    match expr:
        case [a, "+", b]:
            return a + b
        case [a, "-", b]:
            return a - b
        case [a, "*", b]:
            return a * b
        case [a, "/", 0]:
            return "Can't divide by zero"
        case [a, "/", b]:
            return a / b
        case _:
            return "Bad expression"

print(calc([8, "+", 2]))
print(calc([8, "/", 2]))
print(calc([8, "/", 0]))
10
4.0
Can't divide by zero
  1. Given a point as a tuple (x, y), print "origin" for (0, 0), "on the x-axis" when y is 0, "on the y-axis" when x is 0, and otherwise "somewhere else".
Show the answer
def where(point):
    match point:
        case (0, 0):
            return "origin"
        case (x, 0):
            return "on the x-axis"
        case (0, y):
            return "on the y-axis"
        case _:
            return "somewhere else"

for p in [(0, 0), (5, 0), (0, -3), (2, 7)]:
    print(p, where(p))
(0, 0) origin
(5, 0) on the x-axis
(0, -3) on the y-axis
(2, 7) somewhere else

Interview questions

Does Python have a switch statement?

Not by that name. Before Python 3.10 people used if/elif chains or dictionaries of functions. Python 3.10 added match/case, which covers switch-style use and can also match the structure of lists, tuples, dictionaries and objects.

What does case _ mean in a match statement?

_ is the wildcard pattern. It matches any value without storing it, so case _: acts as the default branch. It should be the last case.

Why doesn't case my_variable compare against my_variable's value?

A bare name in a pattern is a capture pattern: it matches anything and binds the subject to that name. To compare against a value, use a literal, a dotted name like Color.RED, or a guard such as case x if x == my_variable.

Key takeaways

  • match checks one value against case patterns from top to bottom; the first match runs and the rest are skipped.
  • case _: is the default and goes last. Use | to give one case several values.
  • Guards (case x if ...) add conditions, but if/elif is clearer for ranges.
  • List and dictionary patterns check the shape of data and capture its parts in one step.
  • A bare name in a case captures a value; it never compares with an existing variable.
  • match needs Python 3.10 or newer.

Frequently asked questions

Is match faster than if-elif in Python?

Not in any way you'd notice. For simple values Python checks the cases one by one, much like an if chain. Choose based on which is clearer to read.

Which Python version introduced match case?

Python 3.10, released in October 2021. The design is described in PEP 634, with a tutorial in PEP 636.

Can I use match with strings?

Yes. String literals like case "yes": are one of the most common uses. Clean the value first with .strip().lower() so "Yes " still matches.

What to learn next

  1. Test everything from this module with Python loop practice: 20 problems.
  2. Learn the data that match unpacks so well in tuples and unpacking.
  3. Revisit Python dictionaries before matching API data.