October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

Python Switch Case: The `match` Statement Explained With Examples

Python 3.10 introduced match and case for switch-style branching and structural pattern matching. Learn the syntax, captures, guards, and common traps.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Python has no traditional switch statement, but Python 3.10 and later provides match and case for branching. The feature is called structural pattern matching: it can compare values, inspect data structures, and capture parts of a match—not merely select a block from a list of constant values.

Basic Python match case syntax

A match statement evaluates its subject once, then tries its case patterns from top to bottom. The first pattern that matches and whose guard, if present, is true runs its case block. The subject can be any expression. This basic example works in Python 3.10 and later:

match status:
    case 400:
        message = "Bad request"
    case 401 | 403:
        message = "Not allowed"
    case 404:
        message = "Not found"
    case _:
        message = "Unknown status"

The | combines alternatives: the second case matches either 401 or 403. The final case _: is a wildcard fallback. If no case matches and there is no fallback, the statement finishes without executing a case block. PEP 634 defines the behavior; the official tutorial introduces it with examples.

How patterns go beyond a conventional switch

Patterns can check part of a value and capture other parts in the same case. For example, this tuple example distinguishes the origin, a point on the y-axis, and other points:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
point = (0, 7)

match point:
    case (0, 0):
        print("origin")
    case (0, y):
        print(f"on the y-axis at {y}")
    case (x, y):
        print(f"point at {x}, {y}")

In (0, y), 0 must match the first element, while y captures the second. Patterns can handle literals, sequences, mappings, class instances, nested structures, alternatives, and captured values. A sequence pattern can also capture a remainder: [first, *rest] binds the first item to first and the remaining items to rest.

Match mapping keys and values

A mapping pattern checks for specified keys and matches their values. Unspecified extra keys are allowed:

match event:
    case {"kind": "click", "x": x, "y": y}:
        print(x, y)
    case _:
        print("other event")

This matches an event with the required values even if it contains additional keys. To capture unmatched entries, use a mapping pattern with **rest.

Inspect class attributes

A class pattern can match an instance and selected attributes. For example, Point(x=0, y=y) checks that the instance’s x attribute is zero and captures its y attribute in y.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Captures, constants, and the wildcard

A bare name in a pattern usually captures a value; it does not compare the subject with an existing variable of the same name. For example, case x: matches anything and binds that subject to x. To compare against a named constant, use a dotted name such as Color.RED. Use a literal such as case 3: for a literal comparison.

The underscore pattern _ is different from a capture name: it matches without binding a name. Put an unguarded catch-all such as case _: last. An irrefutable case—a pattern that cannot fail—cannot be followed by another case unless it has a guard, and only one unguarded irrefutable case is permitted.

Use guards for conditions beyond the pattern

A guard adds a condition after a pattern matches. For example, case Point(x, y) if x == y: first matches the point structure and captures its coordinates, then checks whether they are equal. If the pattern matches but the guard is false, Python tries the following case.

Patterns are not arbitrary Boolean expressions. Put an additional condition in an if guard. If a guard raises an exception, that exception propagates; guards can also have side effects, so keep them straightforward when possible.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Sequence-pattern limits and case bindings

Sequence patterns can match lists and tuples, and the list and tuple spellings have the same pattern meaning. They do not match every iterable: strings and iterators do not match sequence patterns. A successful case’s bindings remain available after the match statement. However, do not depend on names being bound—or remaining unchanged—after a failed partial match; Python leaves those partial-match bindings unspecified.

When to use match

Use match when cases naturally describe the shape or contents of the input, or when matching alternatives and capturing components makes the branching clearer. For a simple choice among a few values, it can still work as a switch-style branch, but Python’s term and broader feature are structural pattern matching. The official tutorial describes it as superficially similar to a switch statement in C, Java, or JavaScript, but more powerful: PEP 636.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.