Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 149 ยท Control Flow

Pattern Matching with match

Learn Python's match statement with literal, capture, wildcard, sequence, mapping and class patterns, plus guards, OR patterns and when to choose if/elif.

The match statement, added in Python 3.10, compares a value against a series of patterns and runs the block for the first one that fits. At first glance it looks like the switch statement from other languages. It's much more than that: patterns can look inside lists, dictionaries and objects, check their shape, and pull out the parts you need in a single step.

This feature is called structural pattern matching. It's ideal for handling commands, parsed JSON, messages with different layouts, and any data where the shape tells you what to do. In this lesson you'll learn each kind of pattern, add conditions with guards, and see when a plain if, elif and else is still the better choice.

The basic shape

A match statement has a subject (the value being examined) and one or more case clauses, each with a pattern:

Python Matching literal values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python tries the cases from top to bottom and runs only the first match. There's no fall-through and no break needed, unlike switch in C or JavaScript.

  • Literal patterns like 200 or "quit" match values equal to them. None, True and False are compared with is, as you learned in Membership and Identity Operators.
  • OR patterns join alternatives with |: case 301 | 302: matches either.
  • The wildcard _ matches anything. Put it last as a catch-all, like else. If no case matches and there's no wildcard, match simply does nothing.

Capture patterns

A bare name in a pattern doesn't compare against a variable. Instead, it captures: it matches anything and binds the value to that name. On its own that's like _, but it becomes useful inside bigger patterns. It also creates a trap worth seeing early:

Python The capture trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first case QUIT: matched "hello" and overwrote QUIT. Python treats any plain name as a capture. Dotted names such as Commands.QUIT (or an enum member, covered in Enums) are compared by value instead.

Warning: case some_variable: never compares with the variable's value. Use a literal, a dotted name, or a guard (shown below).

Sequence patterns

Square brackets (or parentheses) in a pattern match sequences such as lists and tuples, checking their length and elements. Combined with captures, they take a sequence apart. A star captures "the rest", just like unpacking:

Python A tiny command interpreter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice how each case checks the shape and extracts the parts at once:

  • ["go", direction] matches a two-element list whose first item is "go", and binds the second item to direction.
  • ["take", first, *others] matches two or more elements; others becomes a list of the rest.
  • [verb, *_] matches any non-empty list and ignores the rest.

Order matters: ["take", item] must come before the starred version, or the starred one would catch everything.

Strings are deliberately not treated as sequences here, so case [a, b]: won't match the string "ab".

Mapping patterns

Curly braces match dictionaries (and other mappings). A mapping pattern checks that the listed keys exist and that their values match; extra keys are allowed. This makes match excellent for JSON-like data:

Python Handling different events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

**rest captures the remaining key-value pairs. int(delta) is a class pattern: it matches only if the value is an int, then binds it. The if delta < 0 part is a guard.

Guards

A guard is an if condition added after a pattern. The case matches only if the pattern fits and the guard is true. Guards let you compare against variables or check ranges, which patterns alone can't do:

Python Guards

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

If a guard is false, Python moves on to the next case, exactly as if the pattern hadn't matched.

Class patterns

A class pattern like Point(x=0, y=y) checks that the subject is an instance of Point and then matches its attributes. Built-in types work too: str(), int(n), list(items).

Python Matching objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Data classes (from Data Classes) support positional patterns like Rectangle(w, h) automatically. For your own regular classes, use keyword form (Rectangle(width=w)) or define __match_args__.

You can also name a matched sub-pattern with as: case [("go" | "walk") as verb, place]: binds whichever word matched to verb.

A cheat sheet of pattern types

Here's every pattern type from this lesson side by side:

Pattern Example Matches
Literal case 404: a value equal to 404
OR case "y" | "yes": either alternative
Wildcard case _: anything, binds nothing
Capture case name: anything, binds it to name
Value case Color.RED: a value equal to a dotted constant
Sequence case [x, y, *rest]: a list or tuple of 2+ items
Mapping case {"id": id_}: a dict that has the key "id"
Class case Point(x=0): a Point whose x is 0
AS case [_, _] as pair: a two-item sequence, bound to pair

Patterns nest freely, so a mapping can contain a sequence that contains a class pattern. That nesting is what makes match so expressive with real-world data.

match or if?

match is the better tool when you branch on the structure of data: lists of different lengths, dictionaries with different keys, objects of different classes. It removes a lot of len() checks, indexing and isinstance() calls.

For simple comparisons on a single value, ranges, or unrelated conditions, if/elif is shorter and clearer. Don't rewrite if score >= 90: as a match with guards; that adds noise without adding meaning. And because match needs Python 3.10 or newer, code that must support older versions has to stick with if.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens in match x: when no case matches and there is no case _?

    An unmatched match statement silently does nothing.
  2. 2. Given limit = 10, what does case limit: do?

    A bare name is a capture pattern. Use a dotted name or a guard like case n if n == limit: to compare.
  3. 3. Which pattern matches ["add", "milk", "eggs", "tea"] and puts all the items in one list?

    The star captures every remaining element as a list. ["add", item] would only match a two-element list.
  4. 4. Which subject does case {"id": int(n)}: match?

    Mapping patterns allow extra keys, and int(n) requires the value to be an int, so the string "7" does not match.
  5. 5. What is a guard?

    A guard, written case pattern if condition:, lets a case match only when the extra condition holds.

Summary

  • match subject: tries each case from top to bottom and runs only the first match; there's no fall-through.
  • Literal patterns compare values, | combines alternatives, and _ is the catch-all.
  • A bare name captures the value; use dotted names or guards to compare with constants.
  • Sequence patterns (["go", direction], [first, *rest]) and mapping patterns ({"type": t, **rest}) check shape and extract parts.
  • Class patterns like Circle(radius=r) and int(n) check the type and match attributes.
  • Guards (case p if condition:) add extra conditions; use match for structure and if for simple comparisons.

Next: for Loops, where you'll repeat code once for every item in a collection.