Structural Pattern Matching in Python
Python is a very efficient language but some of the features are not in python. Python 3.10 is feature-packed. Unlike other languages such as Java, Python doesn’t have a switch/case statement.
In v3.10, python developers have introduced “Structural Pattern Matching”, we know it as switch/case statements. In the official 3.10 release notes the feature is named “Structural Pattern Matching”, it can be found in PEP 634 (latest).
Value can be provided in a pattern matching statement and it will be matched with several cases. Output statements are executed based on the case match.
Syntax:
Here input value will be matched with each case pattern, in case no case matches, a wildcard case will be executed.
Note: Wildcard case is optional.
Example:
Output:
GeeksForGeeks
Note: To run the code you require latest python setup.
Same logic with if-else:
Output:
GeeksForGeeks
You can combine several cases in one by using | (“or”)
case "read" | "write" | "learn":
print("GeeksForGeeks")
Patterns with literal or variable:
Output:
Sum = 11
Importance of Structural Pattern Matching:
- It makes the code more readable and clean
- With the use of pattern matching, checking a large number of test cases become very easy.
- Pattern matching is faster than multiple if-else blocks.
For more deep knowledge such as pattern grouping, pattern sequence and values, you can refer to the official documentation: PEP 634.
Show some ❤️ by following me and if you like the article please give it a clap. To connect with me on other platforms visit my linktree: https://linktr.ee/kanavarora