Skip to main content

3.2 match Statement and Loop Patterns

Structural pattern matching (match/case) is available in Python 3.10+.

Basic literal matching

def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case _:
return "Unknown"

Pattern matching notes

  • First matching case executes.
  • _ is wildcard pattern.
  • Patterns can bind names.
  • Guards (case pattern if condition) add extra checks.

Loop patterns to prefer

  • Use enumerate(iterable) when index + value are needed.
  • Use direct iteration over collections instead of index loops where possible.
  • Avoid mutating a collection while iterating over it directly.

Official references