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
caseexecutes. _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
- Tutorial match section: https://docs.python.org/3/tutorial/controlflow.html#match-statements
- Language reference
match: https://docs.python.org/3/reference/compound_stmts.html#the-match-statement