Skip to contentSkip to navigation

Module 16 · Lesson 02

Structural Pattern Matching

Pick data apart by its shape with match and case: literal, wildcard and or-patterns, capturing values, sequence and mapping patterns, class patterns, guards, and the traps of bare names and case order.

  • About 9 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Match literals and or-patterns
  • Capture parts of a list
  • Match dictionaries and objects
  • Watch cases get tried in order

Match data by its shape

match compares a value with patterns, top to bottom, and runs the first case that fits.

  • Literals

    case "quit": matches one exact value. | between values means or.

  • Capture

    case ["go", where]: matches a two-item list and names the second item.

  • Shapes

    Patterns can be lists, dictionaries or objects, nested inside each other.

  • Guards

    case int(n) if n > 0: adds a test after the shape matches.

match everywhere

Any time data comes in different shapes, match keeps the code tidy.

  • Game commandsTurn "go north" or "take lamp" into actions.
  • Web repliesReact to a status of 200, 404 or 500 in different ways.
  • Command linesPick apart ["add", name] or ["remove", name, "--force"].
  • EventsHandle {"type": "click", "x": x, "y": y} and other event shapes.

Reading a case line

This case matches a two-word command, but only when the direction is a real exit. Tap each part to see its job.

Part 1 of 5

Tap any part of the code below, or press Next.1 of 5 explored

case:One pattern to try. The first case that fits wins.

Pick data apart with match

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6Literals and or

Each case compares with exact values. _ catches everything else.

Your turn: Add a case for 500 that returns "Server error".

Python
def reply(status):
    match status:
        case 200:
            return "OK"
        case 301 | 302:
            return "Moved"
        case 404:
            return "Not found"
        case _:
            return "Something else"

for code in [200, 302, 404, 500]:
    print(code, reply(code))
Output
Press Run to see what it prints.

Watch cases get tried in order

Press Step to run one line at a time. Watch the names box change.

Ready. Press Step to run the first line.

  1. def locate(point):
  2. match point:
  3. case (0, 0):
  4. return "origin"
  5. case (0, y):
  6. return f"up {y}"
  7. case (x, y) if x == y:
  8. return f"diagonal {x}"
  9. case (x, y):
  10. return f"at {x},{y}"
  11. print(locate((0, 3)))
  12. print(locate((2, 2)))
  13. print(locate((4, 1)))

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.Which case wins?

match 5:
    case int():
        print("int")
    case 5:
        print("five")

0 of 6 answered

Common match misconceptions

Each card is something learners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

match and case

A match statement compares one value, the subject, against a list of patterns, top to bottom. The first case whose pattern fits runs, and the rest are skipped:

Try it 1: edit me, then Run
def describe(status):
    match status:
        case 200:
            return "OK"
        case 404:
            return "Not found"
        case 500 | 502 | 503:
            return "Server error"
        case _:
            return "Something else"
Output
Press Run to see what it prints.
  • A literal pattern such as 200 or "quit" matches an equal value.
  • | makes an or-pattern: any of the alternatives may match.
  • _ is the wildcard: it matches anything and is the usual last case, like a final else.

If no case matches and there is no wildcard, nothing happens: the match statement simply does nothing, which can hide a missing case. Adding case _: that handles or reports the unexpected is a good habit.

So far this is just a neater if/elif. The real power is in the next patterns.

Capturing values

A plain name in a pattern is a capture pattern. It matches anything and stores the value in that name:

Try it 2: edit me, then Run
match command.split():
    case ["go", direction]:
        print("You walk", direction)
    case ["take", item]:
        print("You pick up", item)
    case ["quit"]:
        print("Bye")
Output
Press Run to see what it prints.

["go", direction] is a sequence pattern: it matches a list or tuple of exactly two items whose first item is "go", and binds the second to direction. In one line it checks the type, the length and the first word, and extracts the argument.

To match sequences of different lengths, use a star:

Try it 3: edit me, then Run
match words:
    case []:
        print("empty")
    case [first]:
        print("one word:", first)
    case [first, *rest]:
        print(first, "and", len(rest), "more")
Output
Press Run to see what it prints.

*rest collects any remaining items into a list, possibly empty. Strings are deliberately not treated as sequences by these patterns, so case [a, b]: never matches the text "hi".

Mapping patterns

A dictionary pattern matches dictionaries that have the listed keys:

Try it 4: edit me, then Run
match event:
    case {"type": "click", "x": x, "y": y}:
        print(f"click at {x},{y}")
    case {"type": "key", "key": key}:
        print("pressed", key)
Output
Press Run to see what it prints.

Extra keys in the subject are allowed and ignored, which suits JSON data that may gain fields over time. Literals check values ("type": "click"), and names capture them ("x": x). Use **rest to collect the other keys if you need them.

Class patterns

A class pattern checks the type of an object and, optionally, its attributes:

Try it 5: edit me, then Run
from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float

match p:
    case Point(x=0, y=0):
        print("origin")
    case Point(x=0, y=y):
        print("on the y axis at", y)
    case Point():
        print("somewhere else")
Output
Press Run to see what it prints.

Point(x=0, y=y) means "a Point whose x equals 0; capture its y". For built-in types, int(n) or str(s) matches by type and binds the whole value. Dataclasses also allow positional patterns such as Point(0, y).

Guards and as

A guard adds an if condition to a case. The case only matches if the pattern fits and the condition is true:

Try it 6: edit me, then Run
match order:
    case {"total": total} if total >= 100:
        print("free delivery")
    case {"total": total}:
        print("delivery costs 4.99")
Output
Press Run to see what it prints.

as binds the part matched by a sub-pattern to a name, which is handy with or-patterns: case ("rock" | "paper" | "scissors") as move:.

Trap: a bare name never compares

Because a plain name captures, it cannot be used to compare against a variable:

Try it 7: edit me, then Run
QUIT = "q"
match key:
    case QUIT:          # captures anything into QUIT!
        ...
Output
Press Run to see what it prints.

This case matches every value and overwrites QUIT. Python even refuses to run code where such a case is followed by others, with the error "name capture makes remaining patterns unreachable". To compare against a constant, use a literal (case "q":) or a dotted name, such as Keys.QUIT from a class or an enum: dotted names are treated as values, not captures.

Trap: order matters

Cases are tried in order, so put specific shapes before general ones. If case [first, *rest]: came before case [first]:, a one-word list would match the first case (with an empty rest) and the one-word case would never run.

When to use match

Use it when you branch on the structure of data: commands, messages, parsed JSON, tokens, trees. For a simple choice between values, a dictionary lookup or if/elif is often just as clear. Pattern matching shines when each branch would otherwise start with checks like isinstance(x, list) and len(x) == 2 and x[0] == "go".

Syntax

The general shape of the statements in this lesson.

syntax.py
match subject:
    case 1 | 2 | 3:              # literals, or-pattern
        ...
    case [x, y]:                 # sequence of exactly two, captured
        ...
    case [first, *rest]:         # one or more
        ...
    case {"type": "a", "id": n}: # mapping: keys required, extras ignored
        ...
    case Point(x=0, y=y):        # class and attributes
        ...
    case int(n) if n > 0:        # type pattern with a guard
        ...
    case ("a" | "b") as letter:  # name the matched part
        ...
    case Colour.RED:             # dotted name: compares, does not capture
        ...
    case _:                      # wildcard: anything else
        ...
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

A text adventure command parser

Beginner

Parse commands typed by a player: go with a direction, take with one or more items, look, and quit (also q or exit). Report anything else, including a direction that is not allowed.

Python
def handle(command):
    match command.lower().split():
        case ["go", ("north" | "south" | "east" | "west") as direction]:
            return f"You walk {direction}."
        case ["go", other]:
            return f"You cannot go {other}."
        case ["take", item]:
            return f"You take the {item}."
        case ["take", first, *others]:
            return f"You take the {first} and {len(others)} more."
        case ["look"]:
            return "You see a quiet forest."
        case ["quit"] | ["q"] | ["exit"]:
            return "Goodbye."
        case []:
            return "Say something."
        case _:
            return f"I do not understand {command!r}."

for typed in ["go north", "go up", "take lamp", "take key map rope", "LOOK", "q", "", "dance wildly"]:
    print(handle(typed))
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

Each case states one shape of command. The or-pattern inside the first case accepts only the four directions and names the match with as; any other direction falls to the next case. The single-item take comes before the starred one, an empty list catches blank input, and the wildcard reports the rest.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

A bare name that captures everything

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
STOP = 'stop'

def react(word):
    match word:
        case STOP:
            return 'halt'

print(react('go'))
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints halt for every word, including go

Write this instead

def react(word):
    match word:
        case 'stop':
            return 'halt'
        case _:
            return 'carry on'

print(react('go'))

Why it happens

STOP in a case is a capture pattern: it matches any value and stores it in STOP.

In the real world

Where this shows up in software people use every day.

  1. Handling payment webhooks

    Payments

    A shop receives JSON events from its payment provider: payments that succeed or fail, and refunds. Events carry extra fields the shop ignores, and the provider adds new event types over time. One match statement routes every event, and unknown ones are logged rather than crashing the handler.

    Why Python fits

    Mapping patterns check exactly the keys each kind of event needs and ignore extras such as currency. The refund cases show a guard: a positive whole-number amount is refunded, and the next case catches zero. A typed capture str(kind) logs future event types, and the wildcard rejects anything without a type at all.

    Python
    events = [
        {"type": "payment", "status": "succeeded", "order": "A17", "amount": 4999, "currency": "usd"},
        {"type": "payment", "status": "failed", "order": "A18", "reason": "card_declined"},
        {"type": "refund", "order": "A11", "amount": 1500},
        {"type": "refund", "order": "A12", "amount": 0},
        {"type": "dispute", "order": "A05"},
        {"note": "malformed"},
    ]
    
    def route(event):
        match event:
            case {"type": "payment", "status": "succeeded", "order": order, "amount": amount}:
                return f"ship {order} (paid {amount / 100:.2f})"
            case {"type": "payment", "status": "failed", "order": order, "reason": reason}:
                return f"email customer about {order}: {reason.replace('_', ' ')}"
            case {"type": "refund", "order": order, "amount": int(amount)} if amount > 0:
                return f"refund {amount / 100:.2f} on {order}"
            case {"type": "refund", "order": order}:
                return f"ignore empty refund on {order}"
            case {"type": str(kind)}:
                return f"log unknown event type {kind!r}"
            case _:
                return "reject malformed event"
    
    for event in events:
        print(route(event))
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Is match the same as a switch statement in other languages?

It can be used like one, but it does far more: it matches shapes, types and nested structures and binds values. There is also no fall-through: exactly one case runs.

Does match work on strings character by character?

No. Sequence patterns deliberately ignore str, bytes and bytearray, so a string only matches literal or capture patterns. Split it first, as the command parser does, to match its words.

Can patterns be nested?

Yes. case {"items": [{"sku": sku}, *_]}: matches a dictionary whose items list starts with a dictionary that has a sku, and captures it. Nesting is where pattern matching saves the most code.

Which Python version do I need?

Python 3.10 or newer. Earlier versions report a syntax error at match. The browser Python used by this course is newer, so every example here runs.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 19 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.