Match. Suppose we have a variable, either a simple one like an Int or a more complex tuple or list, and want to test its contents. A Python match statement can help with this requirement.
While an if-statement could work instead of match, the match syntax is more elegant and can make programs more maintainable. Match usually results in shorter code.
Example. This program has several possible match statements, each with various case statements. It is meant to demonstrate many possible ways of using match.
Part 1 We have a variable with value 10, and it does not match the cases 5 or 7, so it is matched by the default case (with the underscore).
Part 2 We can use a guard clause (an if statement as part of a case) to only reach a case if the expression evaluates to true.
Part 3 Sometimes we have a complex variable (like a tuple) and only want to match part of it. We can capture the unmatched part as a variable.
# Part 1: use simple match statement with default case.
value = 10
match value:
case 5:
print("Five matched!")
case 7:
print("Seven matched!")
case _:
print("Default case")
# Part 2: use if statement inside case statement.
done = True
match value:
case 10 if done:
print("Done, case 10 matched")
case _:
print("Not reached")
# Part 3: capture a variable as part of a case statement inside a match.
animal = ("bird", 10)
match animal:
case ("cat", weight):
print("Cat weight is", weight)
case ("bird", weight):
print("Bird weight is", weight)
# Part 4: use multiple cases in a single statement.
code = 10
match code:
case 5 | 10 | 15:
print("Multiple of 5")
case _:
print("Not reached")
# Part 5: match a list.
items = ["bird", "frog", "dog"]
match items:
case []:
print("Empty")
case ["bird", "frog", x]:
print("Matched bird, frog and", x)Default case
Done, case 10 matched
Bird weight is 10
Multiple of 5
Matched bird, frog and dog
Summary. It is possible to replace if-statements with equivalent match-statements in Python, and this can sometimes simplify the syntax of programs.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.