match

In Python, the match soft keyword allows you to perform structural pattern matching. It allows you to check a value against a series of patterns and execute code based on the first pattern that matches.

Pattern matching with match can be seen as a more powerful and flexible version of ifelifelse chains. The match keyword simplifies complex branching logic, making your code more readable and expressive.

Python match Keyword Examples

Here’s a quick example of how you can use the match keyword to perform pattern matching:

Python
>>> def http_status(status):
...     match status:
...         case 200:
...             return "OK"
...         case 404:
...             return "Not Found"
...         case 500:
...             return "Internal Server Error"
...         case _:
...             return "Unknown status"
...

>>> http_status(200)
'OK'
>>> http_status(404)
'Not Found'
>>> http_status(403)
'Unknown status'

In this example, the http_status() function uses a match statement to compare the status argument against several patterns (200, 404, 500). If none of these patterns matches the input argument, then the wildcard pattern (_) is used as a fallback, returning "Unknown status".

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 May 23, 2025