0
0
PythonHow-ToBeginner · 3 min read

How to Use Match Case with Multiple Values in Python

In Python, you can use 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.
python
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.

python
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)
Output
Number is 1, 2, or 3 Number is 4 or 5 Number is something else
⚠️

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.

python
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")
Output
No match Matched 1 or 2
📊

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 _:

Key Takeaways

Use the pipe operator '|' to match multiple values in one case.
Never use 'or' inside a case; it does not work as expected.
The default case is written as 'case _:' to catch unmatched values.
Match-case makes code cleaner by grouping multiple values in one block.