๐ฏStructural Pattern Matching (match/case)LESSON~15 min
Structural Pattern Matching (match/case)
Introduced in Python 3.10, match/case is one of the most powerful additions to the language. It goes far beyond a simple switch statement โ it can destructure data, match shapes, and guard on conditions.
Basic Syntax
The _ wildcard is like else โ it matches anything. Unlike if/elif, there is no fallthrough between cases (unlike C/Java switch).
Matching Literals
You can match integers, floats, strings, booleans, and None:
OR Patterns (|)
Use | to match multiple values in one case:
Matching Sequences
Match against lists, tuples, and other sequences. Use *rest for variable-length sequences:
Note: the captured variables (x, y, z, rest) are available in the case body.
Matching Mappings (Dicts)
Match dict-like objects by key presence and value:
Mapping patterns only check the specified keys โ extra keys in the dict are allowed.
Matching Class Instances
Match against class instances using ClassName(attr=pattern):
Guard Clauses (if)
Add an if guard to a case for additional filtering:
Wildcard _ and Capture Variables
When to Use match vs if/elif
Use match when:
You're dispatching on the structure or type of data
You need to destructure and capture parts of the data
You have many cases based on a single value's identity
Use if/elif when:
Conditions involve multiple variables
You need more complex boolean logic
Targeting Python < 3.10 for compatibility
Knowledge Check
What Python version introduced the match/case statement?
In a match statement, what does the _ pattern do?
How do you add an extra condition to a match case?