How to Use Match Case with Multiple Values in Python
match with case to check multiple values by listing them separated by pipes inside the case, like case 1 | 2 | 3:. This matches if the variable equals any of those values, allowing concise handling of multiple cases in one block.Syntax
The match statement compares a variable against different case patterns. To match multiple values in one case, separate them with the pipe | operator. This means the case matches if the variable equals any of those values.
match variable:starts the pattern matching.case val1 | val2 | ...:matches if variable equals any listed value.case _:is the default case if no other matches.
match value:
case 1 | 2 | 3:
print("Value is 1, 2, or 3")
case 4 | 5:
print("Value is 4 or 5")
case _:
print("Value is something else")Example
This example shows how to use match with multiple values in one case. It prints a message depending on which group the number belongs to.
def check_number(value): match value: case 1 | 2 | 3: print("Number is 1, 2, or 3") case 4 | 5: print("Number is 4 or 5") case _: print("Number is something else") check_number(2) check_number(5) check_number(10)
Common Pitfalls
A common mistake is to try using or inside a case like case 1 or 2:, which does not work as expected because it evaluates to a single value. Instead, always use the pipe | operator to list multiple values.
Also, avoid using parentheses to group multiple values as a tuple, because case (1, 2): matches a tuple value, not multiple individual values.
value = 2 # Wrong way - does not match multiple values match value: case 1 or 2: print("Matched 1 or 2") # This will always match 1 because '1 or 2' evaluates to 1 case _: print("No match") # Right way match value: case 1 | 2: print("Matched 1 or 2") case _: print("No match")
Quick Reference
Use the pipe | operator to list multiple values in a case. The match statement compares the variable to each value separated by pipes.
- Syntax:
case val1 | val2 | ...: - Do not use:
case val1 or val2: - Default case:
case _: