Making Decisions · Lesson 10 of 39
Pattern Matching with match and case
Many languages have a switch statement. Python's version, match, arrived in Python 3.10 and does much more: it can match not only single values but also the shape of data – lists, tuples and dictionaries – and pull values out of them in the same step.
In this lesson
- Matching simple values, the wildcard
_and alternatives with| - Adding conditions with guards (
if) - Matching sequences and dictionaries
- When
matchis clearer thanif/elif
Matching values
status = 404
match status:
case 200:
message = "OK"
case 301 | 302:
message = "Redirect"
case 404:
message = "Not found"
case 500:
message = "Server error"
case _:
message = "Unknown status"
print(status, message)
404 Not found
- Python checks each
casefrom top to bottom and runs the first one that matches. There is no "fall-through" and nobreakneeded. |means "or":case 301 | 302matches either code.case _is the wildcard: it matches anything, so it works likeelse. Put it last.
How match picks a case
- Evaluate the subject
status→ 404 - Try each case in order200? 301 | 302? 404 ✓
- Run that block onlymessage = "Not found"
- Continue after matchno fall-through to other cases
Guards: adding a condition
A case can capture the value into a name and then test it with if:
def describe(temp):
match temp:
case t if t < 0:
return "freezing"
case t if t < 20:
return "cool"
case t if t < 35:
return "warm"
case _:
return "hot"
for value in [-3, 12, 28, 41]:
print(value, describe(value))
-3 freezing 12 cool 28 warm 41 hot
For plain number ranges like this, if/elif is just as clear. Guards shine when combined with the structural patterns below.
Matching sequences (lists and tuples)
This is where match beats if/elif. Imagine a tiny command interpreter for a game:
def run(command):
match command.split():
case ["quit"]:
return "Goodbye!"
case ["go", direction]:
return f"You walk {direction}."
case ["take", item, "from", place]:
return f"You take the {item} from the {place}."
case ["drop", *items]:
return f"You drop: {', '.join(items)}"
case _:
return "I don't understand."
print(run("go north"))
print(run("take key from table"))
print(run("drop map torch rope"))
print(run("dance"))
You walk north. You take the key from the table. You drop: map, torch, rope I don't understand.
Each pattern checks the length and the fixed words, and binds the variable parts (direction, item, place) to names. *items collects any number of remaining words.
Matching dictionaries
Data from web APIs usually arrives as dictionaries. A mapping pattern checks that certain keys exist (extra keys are allowed) and extracts their values:
events = [
{"type": "payment", "amount": 499, "currency": "INR"},
{"type": "refund", "amount": 120},
{"type": "login", "user": "neha"},
{"type": "unknown"},
]
for event in events:
match event:
case {"type": "payment", "amount": amount, "currency": cur}:
print(f"Received {amount} {cur}")
case {"type": "refund", "amount": amount}:
print(f"Refunded {amount}")
case {"type": "login", "user": name}:
print(f"{name} logged in")
case _:
print("Ignored event")
Received 499 INR Refunded 120 neha logged in Ignored event
Common mistake: using a plain variable name as a constant
case RED: does not compare with a variable called RED – a bare name is a capture pattern that matches anything and assigns to it. Python even reports "name capture 'RED' makes remaining patterns unreachable". Compare against constants with a dotted name such as case Color.RED: (an Enum) or use a guard.
match or if/elif?
| Situation | Better choice |
|---|---|
Ranges and comparisons (marks >= 75) | if/elif |
| Many fixed values (status codes, menu options) | either – match reads well |
| Checking the shape of lists, tuples or dicts and pulling out parts | match |
| Code that must run on Python 3.9 or older | if/elif |
Practice
Try it yourself
Write a
matchthat turns a day number (1–7) into "Weekday" or "Weekend" (6 and 7), and anything else into "Invalid".Show solution
for day in [3, 7, 9]: match day: case 1 | 2 | 3 | 4 | 5: print(day, "Weekday") case 6 | 7: print(day, "Weekend") case _: print(day, "Invalid")3 Weekday 7 Weekend 9 Invalid
Match a point tuple
(x, y): print "origin" for (0, 0), "on the x-axis" when y is 0, "on the y-axis" when x is 0, otherwise its coordinates.Show solution
for point in [(0, 0), (5, 0), (0, -2), (3, 4)]: match point: case (0, 0): print("origin") case (x, 0): print(f"on the x-axis at {x}") case (0, y): print(f"on the y-axis at {y}") case (x, y): print(f"at ({x}, {y})")origin on the x-axis at 5 on the y-axis at -2 at (3, 4)
Quick check
Which Python version introduced match?
Python 3.10.
What does case _: do?
It is the wildcard: it matches anything, like else.
Does a dict pattern {"type": "refund"} match {"type": "refund", "amount": 5}?
Yes. Mapping patterns only require the listed keys; extra keys are allowed.
Summary
matchtries eachcasein order and runs only the first match.- Use
|for alternatives,_as the catch-all andifguards for extra conditions. - Sequence and mapping patterns check the shape of data and extract values in one step.
Practise decisions and loops interview-style: Python control flow, functions and scope questions.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.