← All notes

Python match statements compare a subject against case patterns

Answer: A match statement compares the value of an expression with successive case patterns. Only the first matching pattern runs. If no pattern matches, no branch is executed.

Pattern forms

The simplest form compares a subject value against literals; combine several literals in a single pattern using |. The _ pattern is a wildcard that never fails. Sequence patterns bind variables from a subject value, similar to unpacking assignment. Class patterns can capture attributes into variables.

Guards

A guard is the keyword if followed by an expression. The guard is part of the case, not the pattern. The guard runs only after its pattern matches and pattern variables are bound.

Background

PEP 636 is tutorial material for the pattern matching introduced by PEP 634.

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: Python docs (tutorial), More Control Flow Tools: match statements, PSF-2.0 (https://raw.githubusercontent.com/python/cpython/main/LICENSE); Python Enhancement Proposals, PEP 636 – Structural Pattern Matching: Tutorial, Public domain or CC0-1.0 (https://peps.python.org/pep-0636/#copyright). Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Python docs (tutorial), More Control Flow Tools: match statements, PSF-2.0 (https://raw.githubusercontent.com/python/cpython/main/LICENSE); Python Enhancement Proposals, PEP 636 – Structural Pattern Matching: Tutorial, Public domain or CC0-1.0 (https://peps.python.org/pep-0636/#copyright).

Cite this

Permanent ID: iil:note:7aqsbdr8

iinventedlight. 2026. "Python match statements compare a subject against case patterns." iinventedlight Library, iil:note:7aqsbdr8, version of 2026-11-16. https://iinventedlight.com/library/notes/python-structural-pattern-matching/. License: CC-BY-4.0.

@misc{iil_note_7aqsbdr8,
  author = {{iinventedlight}},
  title = {{Python match statements compare a subject against case patterns}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-16},
  url = {https://iinventedlight.com/library/notes/python-structural-pattern-matching/},
  note = {Permanent ID iil:note:7aqsbdr8. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/python-structural-pattern-matching.md.