Python For Beginners: match Statement in Python 3.10.2
Introduced in Python 3.10, it’s the equivalent of the switch statement found in other programming languages
If you’re familiar with programming languages such as Java or JavaScript, you may know about the switch statement. It can replace if else blocks. Here’s an example of the switch statement in Java,
int letter = 1;
switch (letter) {
case 1:
System.out.println("A");
break;
case 2:
System.out.println("B");
break;
case 3:
System.out.println("C");
break;
default:
System.out.println("D");
}Similar to the switch above, from Python version 3.10, you can use the match statement.
Basic syntax
It takes an expression value and compares it with patterns in case blocks.
def day_of_week (day):
match day:
case 1:
return "Sunday"
case 2:
return "Monday"
case 3:
return "Tuesday"
case _:
return "Invalid day"print(day_of_week(3))Comparing with the switch statement above, the _ at the end of the matchis equivalent to the default block. It executes something when no other case satisfies. It’s like the else block in a if condition.
A single case block also accepts the combination of multiple values. See the line in bold in the snippet of code below.
def day_of_week (day):
match day:
case 1:
return "Sunday"
case 2:
return "Monday"
case 3:
return "Tuesday"
case 4 | 5 | 6:
return "Another day of the week"
case _:
return "Invalid day"print(day_of_week(2))Result,
MondayPattern matching on other types of expressions
Pattern matching in Python 3.10 accepts things such as lists and tuples as well, not only a single value expression.
You can match the general pattern of the list. For instance, the expression is a single item list or a two-item list.
You can also match the general pattern and the list's values. For instance, the expression is a two-item list, and the second item is the number two.
You can even use if statements and pattern match to a list of any number of elements. See the two cases in bold in the code below.
for element in [["A","B","C"],[11],[45,45],[7,8,9,7],["Sunday"], ["Sunday", "Monday"],"string element"]:
match element:
case [x]:
print(f"List with one item: {x}")
case [x,y] if x == y:
print("List with two items of same value")
case [x,"Monday"]:
print(f"List with two items: {x} and Monday")
case [x,"Tuesday"]:
print(f"List with two items: {x} and Tuesday")
case [x,y,z]:
print(f"List with three items: {x}, {y} and {z}")
case [*x]:
for i in x:
print(i)
case _:
print("Case not handled")Result,
List with three items: A, B and C
List with one item: 11
List with two items of same value
7
8
9
7
List with one item: Sunday
List with two items: Sunday and Monday
Case not handledReference:
Thanks for reading. More on Python:
