This is a quick syntax reference for Python pattern matching.

Example 1:

match point:
    case (0, 0):
        print("Origin")
    case (0, y):
        print(f"Y={y}")
    case (x, 0):
        print(f"X={x}")
    case (x, y):
        print(f"X={x}, Y={y}")
    case _:
        raise ValueError("Not a point")

Matching List

Match head and tail

match list:
    case [head, *tail]:
        # do something

Or Pattern

match list:
    case [] | [_]:
        # list of zero or one element
    case [first, second, *tail]:
        # do something

Guard

match command.split():
    case [x] if x > 10:
        # do something

Footnotes

  1. PEP 636 – Structural Pattern Matching: Tutorial | peps.python.org