Match-Case (Python 3.10+)

Pattern matching in Python

Interview Relevant: Modern Python feature

Match-Case

Structural pattern matching (Python 3.10+).

Code Examples

Pattern matching in Python 3.10+.

python
1# Basic match-case
2def http_status(status):
3    match status:
4        case 200:
5            return "OK"
6        case 404:
7            return "Not Found"
8        case 500:
9            return "Server Error"
10        case _:  # Default case
11            return "Unknown"
12
13# Pattern matching with structure
14def process(data):
15    match data:
16        case [x]:
17            print(f"Single: {x}")
18        case [x, y]:
19            print(f"Pair: {x}, {y}")
20        case [x, *rest]:
21            print(f"First: {x}, Rest: {rest}")
22
23# Guard clauses
24match point:
25    case (x, y) if x == y:
26        print("On diagonal")
27    case (x, y):
28        print(f"Point: {x}, {y}")
29
30# Class patterns
31match obj:
32    case Point(x=0, y=0):
33        print("Origin")
34    case Point(x, y):
35        print(f"Point({x}, {y})")

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In