The match
statement is a powerful feature introduced in Python 3.10 that enables pattern matching. It allows you to match variables or objects against patterns and execute code based on the match.
The general syntax of the match
statement is:
match subject:
case pattern1:
# code block
case pattern2:
# code block
case _:
# default case
subject
: The variable or expression being matched.case
: A pattern to match against the subject._
: The wildcard pattern used as a default when no other patterns match.match value:
case 1:
print("Value is 1")
case 2:
print("Value is 2")
case _:
print("Value is something else")
value
is 1, it prints Value is 1
.value
is 2, it prints Value is 2
.Value is something else
.You can match based on the type of the subject.
match data:
case int():
print("Data is an integer")
case str():
print("Data is a string")
case list():
print("Data is a list")
case _:
print("Data is of an unknown type")
The match
statement can unpack tuples and perform actions based on their structure.
match point:
case (0, 0):
print("Point is at the origin")
case (x, 0):
print(f"Point is on the x-axis at {x}")
case (0, y):
print(f"Point is on the y-axis at {y}")
case (x, y):
print(f"Point is at ({x}, {y})")
case _:
print("Invalid point")
You can also match dictionary patterns using the match
statement.
match person:
case {"name": name, "age": age}:
print(f"Name: {name}, Age: {age}")
case {"name": name}:
print(f"Name: {name}, Age is unknown")
case _:
print("Invalid person data")
You can add conditions to patterns using if clauses.
match number:
case x if x > 0:
print("Number is positive")
case x if x < 0:
print("Number is negative")
case 0:
print("Number is zero")
match
Statement in PythonObjective: Enhance your understanding of the match
statement by applying it to solve practical problems.
Match Simple Values:
Write a Python function match_day_of_week(day)
that prints the name of the day based on a number input (1 for Monday, 7 for Sunday).
def match_day_of_week(day):
match day:
case 1:
return "Monday"
case 2:
return "Tuesday"
case 3:
return "Wednesday"
case 4:
return "Thursday"
case 5:
return "Friday"
case 6:
return "Saturday"
case 7:
return "Sunday"
case _:
return "Invalid day"
print(match_day_of_week(3)) # Output: Wednesday
Match Data Structures:
Write a function match_list_contents(data)
that matches different types of lists (e.g., an empty list, a list of numbers, or a list with a string).
def match_list_contents(data):
match data:
case []:
return "Empty list"
case [x, y]:
return f"List with two elements: {x}, {y}"
case [x, *rest]:
return f"List with {x} followed by {len(rest)} more elements"
case _:
return "Unknown list format"
print(match_list_contents([1, 2, 3, 4])) # Output: List with 1 followed by 3 more elements
Use Guard Clauses:
Implement a function match_number(num)
that matches numbers and uses guards to print whether they are even or odd, positive or negative.
def match_number(num):
match num:
case n if n > 0 and n % 2 == 0:
return "Positive even number"
case n if n > 0 and n % 2 != 0:
return "Positive odd number"
case n if n < 0 and n % 2 == 0:
return "Negative even number"
case n if n < 0 and n % 2 != 0:
return "Negative odd number"
case _:
return "Zero"
print(match_number(-5)) # Output: Negative odd number
Deconstruct Complex Structures:
Create a function match_nested_data(data)
that uses match
to handle nested structures like lists of dictionaries and tuples.
def match_nested_data(data):
match data:
case [{"name": name, "age": age}]:
return f"Found a person named {name}, aged {age}"
case [(int(x), str(y))]:
return f"Tuple with number {x} and string {y}"
case _:
return "Unknown structure"
print(match_nested_data([{"name": "Alice", "age": 30}])) # Output: Found a person named Alice, aged 30
The match
statement is a versatile feature that simplifies complex condition handling. Mastering it will make your Python code more readable and expressive.