underscore (_)

In Python, the underscore character (_) is a soft keyword that acts as a wildcard for structural pattern matching. You use _ in combination with case when you want to handle all unmatched cases in a match statement.

Underscore (_) Examples

Here’s an example of using the _ soft keyword in a match statement:

Python
>>> def process_value(value):
...     print("Please enter 1, 2, or 3")
...     match value:
...         case 1:
...             print("You chose One.")
...         case 2:
...             print("You chose Two.")
...         case 3:
...             print("You chose Three.")
...         case _:
...             print("Invalid choice.")
... 

>>> process_value(1)
Please enter 1, 2, or 3
You chose One.
>>> process_value(2)
Please enter 1, 2, or 3
You chose Two.
>>> process_value(5)
Please enter 1, 2, or 3
Invalid choice.

The _ acts as a wildcard to handle all unmatched cases in a match statement. In this examle, you use the _ to match any value that isn’t 1, 2, or 3, without binding it to a name.

Tutorial

Structural Pattern Matching in Python

In this tutorial, you'll learn how to harness the power of structural pattern matching in Python. You'll explore the new syntax, delve into various pattern types, and find appropriate applications for pattern matching, all while identifying common pitfalls.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated March 6, 2025 • Reviewed by Philipp Acsany