Content · Programming · Python

Python OR Patterns, AS Patterns, and Wildcards

Combine patterns with |, preserve a matched value with as, and ignore the rest with _.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Combine patterns with |, preserve a matched value with as, and ignore the rest with _.

What You Will Learn


The | operator matches either of two alternatives, while as binds the successful pattern to a name. The wildcard _ does not create a useful binding. Alternatives in an OR pattern must bind the same set of capture names. These features help express a small group of related commands without repetitive branches.

Step-by-Step Example


The example below makes the behavior visible with small input values that you can change safely.

def action(command):
    match command:
        case "quit" | "exit" as selected:
            return f"Closing from {selected}"
        case ["open", path]:
            return f"Open {path}"
        case ["help", _]:
            return "Help with an option"
        case _:
            return "Unknown"

print(action("exit"))
print(action(["open", "notes.txt"]))

How the Example Works


  • The function action defines reusable behavior; its body executes when it is called, not when it is declared.
  • The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.

Expected output from the example:

Closing from exit
Open notes.txt

When You Would Use This


Pattern matching can simplify dispatching application commands or decoding structured messages from a trusted parser. It chooses a branch based on shape and selected values, but application-level validation is still necessary. Compare it with an if/elif chain if the problem only involves simple Boolean expressions.

Practice: Modify the Code


Add an alias for exit and verify that as records the actual spelling.

Verify the changed output against the behavior described above, including the relevant invalid or boundary case.

For complete parameters and version details, consult the official Python documentation.

Common Beginner Mistakes


  • Confusing the wildcard _ with a capture that can be printed later.
  • Using OR alternatives that bind different names in their patterns.

Key Takeaways


  • Combine patterns with |, preserve a matched value with as, and ignore the rest with _.
  • The | operator matches either of two alternatives, while as binds the successful pattern to a name.
  • Apply this operation only after checking the assumptions and input conditions shown in the example.
Share this resourceSend this page to someone who may find it useful.