Python match / case StatementGet Certified
What Is match / case?
The match statement compares one value against a list of patterns and runs the block of the first pattern that fits. It was added in Python 3.10 and is called structural pattern matching. In its simplest form it works like the switch statement of other languages, but it is far more powerful. A pattern can describe the shape of data: a list with three items, a dictionary with certain keys, or an object of a certain class, and it can pick the parts out of that data into variables at the same time.
- Literal patterns: match exact numbers, strings,
True,False, andNone. - Wildcard
_: matches anything and works like a finalelse. - OR patterns:
case "Sat" | "Sun":matches any of several alternatives. - Capture patterns and guards: store the matched value in a variable and add an extra
iftest. - Sequence, mapping and class patterns: take apart lists, tuples, dictionaries, and objects.
Note:matchneeds Python 3.10 or later. In older versions it is aSyntaxError. The code on this page runs in the browser with a modern Python runtime, so you do not need to install anything.
The Basic Syntax and Literal Patterns
A match statement starts with the keyword match, the value to inspect, and a colon. Each case below it, indented one level, holds a pattern and a colon, followed by an indented block. Python tests the cases from top to bottom and runs only the first one that matches. There is no fall-through, so you never need a break. The pattern _, called the wildcard, matches everything, so it is used as the last case for “none of the above”. If no case matches and there is no wildcard, nothing happens and no error is raised.
Try It: A Status Code Lookup
Click Test My Code. Change status to 500, and then to 301, and run it again.
status = 404
match status:
case 200:
print("OK")
case 404:
print("Not Found")
case 500:
print("Server Error")
case _:
print("Unknown status")status refers to the integer 404.match status: tells Python to compare the value of status with the patterns in the case lines below.status equals 200. It does not, so this case is skipped.404 equals the value, so this case matches. Python runs its block and then leaves the whole match statement. The remaining cases are never tested.Not Found._ matches any value. It acts like else and belongs at the end, for the values that none of the other cases handle.OR Patterns
Use the vertical bar | to match one of several alternatives in a single case. This avoids repeating the same block many times. Writing case "Sat" or "Sun": is not correct. The keyword or is evaluated as an ordinary expression and does not make a pattern. Always use | inside patterns.
Try It: Weekday or Weekend
Click Test My Code. Change day to "Wed" and then to "Holiday".
|. Any other text reaches the wildcard.day = "Sat"
match day:
case "Mon" | "Tue" | "Wed" | "Thu" | "Fri":
print("Weekday")
case "Sat" | "Sun":
print("Weekend")
case _:
print("Not a day")day refers to the string "Sat".day with each pattern in turn."Sat" is not among them, so it is skipped."Sat" is one of the two alternatives, so this case matches.Weekend.Capture Patterns and Guards
A pattern that is a plain variable name, such as n, matches any value and stores it in that variable. This is a capture pattern. It is useful together with a guard, an if condition placed after the pattern. The case runs only when the pattern matches and the guard is true. If the guard is false, Python simply tries the next case.
- A capture pattern always matches, so a case with one and no guard must be the last case. Python raises a
SyntaxErrorif a later case could never be reached. - The wildcard
_is a capture pattern that does not store anything. - A bare name captures, it does not compare. To compare with a constant, use a dotted name such as
Color.RED, or a literal.
Try It: Classifying a Number
Click Test My Code. Try number = -3, number = 0, and number = 8.
n and uses guards to test whether it is negative or even. The final capture pattern handles the remaining odd positive numbers.number = 15
match number:
case 0:
print("Zero")
case n if n < 0:
print(n, "is negative")
case n if n % 2 == 0:
print(n, "is even")
case n:
print(n, "is odd")number refers to the integer 15.15 with the cases from top to bottom.15 is not equal to 0, so this case is skipped.n matches any value and stores 15 in n. Then the guard n < 0 is tested. It is false, so Python moves on to the next case.n % 2 == 0 is tested. The remainder of 15 divided by 2 is 1, so the guard is false.15 is odd.Sequence Patterns
A pattern written like a list or a tuple matches a sequence with the same number of items. Each item of the pattern can be a literal, which must be equal, or a variable name, which captures the item. A starred name such as *rest captures all the remaining items as a list. Both [a, b] and (a, b) match lists and tuples alike. Strings and bytes are the exception: they are never matched by sequence patterns, so a string is not split into characters by match.
Try It: A Command Interpreter
Click Test My Code. Add the command ["say", "hi"] to the list and run it again.
commands = [["quit"], ["move", 3, 4], ["say", "hello", "world"], ["jump"]]
for command in commands:
match command:
case ["quit"]:
print("Bye")
case ["move", x, y]:
print(f"Moving to ({x}, {y})")
case ["say", *words]:
print("Saying:", " ".join(words))
case _:
print("Unknown command")commands refers to a list that contains four smaller lists.for loop takes one command at a time and stores it in command. The block below it runs four times.["quit"] matches only a list of exactly one item that equals "quit".Bye.["move", x, y] matches a list of exactly three items whose first item is "move". The second and third items are stored in x and y.["move", 3, 4], the output is Moving to (3, 4).*words collects all the remaining items into a list, however many there are. For ["say", "hello", "world"] the list is ["hello", "world"]." ".join(words) joins the words with spaces. The output is Saying: hello world.["jump"].Unknown command.Try It: Points on a Grid
Click Test My Code. Notice that the order of the cases matters: the most specific case, (0, 0), comes first.
for data in [(0, 0), (5, 0), (0, 7), (2, 3)]:
match data:
case (0, 0):
print("Origin")
case (x, 0):
print("On the x-axis at", x)
case (0, y):
print("On the y-axis at", y)
case (x, y):
print("Point", x, y)data in turn.(0, 0) matches only a pair in which both items equal zero.Origin.x and the second must equal 0. The point (5, 0) matches with x = 5.On the x-axis at 5.0 and the second is captured in y. The point (0, 7) matches with y = 7.On the y-axis at 7.(2, 3).Point 2 3.Mapping Patterns
A pattern written like a dictionary matches a mapping that contains at least the listed keys. The keys in the pattern must be literals, and each value can be a literal or a variable name that captures the value. Unlike sequence patterns, a mapping pattern ignores extra keys, so the dictionary may contain more entries than the pattern mentions. To collect the extra entries, finish the pattern with **rest.
Try It: Handling Events
Click Test My Code. Change the event to {"type": "key", "key": "Enter"} and run it again.
"click" under the key "type" and captures the coordinates. The second case handles keyboard events.event = {"type": "click", "x": 10, "y": 20}
match event:
case {"type": "click", "x": x, "y": y}:
print(f"Click at {x}, {y}")
case {"type": "key", "key": key}:
print("Key pressed:", key)
case _:
print("Unknown event")event refers to a dictionary with three keys."type" with the value "click", and the keys "x" and "y". The values of "x" and "y" are stored in the variables x and y. All the conditions are true, so the case matches.Click at 10, 20."type" equal to "key" and capture the value of "key". It is not reached here.Type and Class Patterns
A pattern that looks like a call, such as int() or str(), checks the type of the value, in the same way as isinstance(). Because it uses isinstance() rules, a class pattern also matches subclasses. This matters for bool, which is a subclass of int: case int(): would also match True, so test bool() first.
The same syntax works with your own classes. Inside the parentheses you can match attributes by name, as in Point(x=0, y=0). Classes created with @dataclass also allow positional patterns, such as Point(0, y).
Try It: Matching by Type
Click Test My Code. Move case bool(): below case int():, run it again, and see how the result for True changes.
values = [42, "hello", 3.5, [1, 2], None, True]
for value in values:
match value:
case None:
print("None")
case bool():
print("bool", value)
case int():
print("int", value)
case float():
print("float", value)
case str():
print("str", value)
case list():
print("list of", len(value))
case _:
print("other")values refers to a list that holds an integer, a string, a float, a list, None, and a Boolean.value in turn.None is a literal pattern that matches only the value None.None.bool() matches any value whose type is bool. It is placed before int() on purpose, because True is also an instance of int.bool True.int() matches the number 42.int 42.float() matches the number 3.5.float 3.5.str() matches the text "hello".str hello.list() matches the list [1, 2].list of 2.Try It: Matching Objects
Click Test My Code. Change the point to Point(3, 0) and then to Point(2, 2).
Point class with @dataclass and creates one object. Class patterns then check the attributes of the object by name and capture the one that is not fixed.from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
p = Point(0, 5)
match p:
case Point(x=0, y=0):
print("Origin")
case Point(x=0, y=y):
print("On the y-axis at", y)
case Point(x=x, y=0):
print("On the x-axis at", x)
case Point():
print("Somewhere else")dataclass decorator writes the constructor and other helper methods of a simple class for you.@dataclass turns the class below into a data class.Point describes a point with two coordinates.x of type int.y of type int.p refers to a point with x = 0 and y = 5.p with the class patterns below.Point, but y is 5 and not 0, so the case does not match.x equals 0, and the value of y is captured in a variable named y. The case matches.On the y-axis at 5.y = 0 and capture x. It is not reached here.Point() with empty parentheses matches any Point object.Tip: Put the most specific pattern first and the most general one last. A general pattern placed early would match first and hide the specific ones below it. Useif/eliffor simple true/false tests, and usematchwhen you compare one value against many shapes or want to unpack data while you test it.
Using match with User Input
The match statement is a natural fit for programs that read commands. Remember that input() returns a string, and that a string is not matched by sequence patterns. Use split() to turn the line into a list of words first, then write patterns for the lists you expect.
Try It: A Four-Function Calculator
The Program Input box is already filled with 12 * 3. Click Run Code straight away, then try 10 / 0, 7 - 2, and hello.
12 * 3 and splits it into three words. A pattern for each operator captures the two numbers as text, and the program converts them to floats. A guard stops a division by zero, and the wildcard reports a wrong format.expression = input("Enter e.g. 12 + 3: ").split()
match expression:
case [a, "+", b]:
print(float(a) + float(b))
case [a, "-", b]:
print(float(a) - float(b))
case [a, "*", b]:
print(float(a) * float(b))
case [a, "/", b] if float(b) != 0:
print(float(a) / float(b))
case [_, "/", _]:
print("Cannot divide by zero")
case _:
print("Use the form: number operator number")input() reads the text 12 * 3, and split() turns it into the list ["12", "*", "3"]."+" in the middle. The middle item is "*", so this case does not match."-", so this case does not match."*", so the case matches. The first and last items are stored as text in a and b.float("12") * float("3") is 36.0. The output is 36.0."/" in the middle, but only if the guard shows that the divisor is not zero._ matches the two numbers without storing them.10 / 0 it would print Cannot divide by zero.hello.Try It: A Text Adventure Parser
The Program Input box is filled with go north. Click Run Code, then try take lamp, go up, exit, and an empty box.
as keyword stores the matched direction in a variable.command = input("Enter a command: ").strip().lower().split()
match command:
case ["go", ("north" | "south" | "east" | "west") as direction]:
print("You walk", direction)
case ["take", item]:
print("You take the", item)
case ["quit" | "exit"]:
print("Goodbye")
case []:
print("Please type something")
case _:
print("Unknown command")strip() removes outer spaces, lower() makes everything lowercase, and split() breaks the text into words. The result is ["go", "north"]."go", and the second must be one of four directions. The as direction part stores whichever direction matched. The parentheses group the alternatives.You walk north."take" followed by any one word, which is captured in item. It is not reached here."quit" or "exit".[] matches exactly that.go up, because "up" is not one of the four directions.Common Mistakes with match / case
- Using Python older than 3.10:
matchraises aSyntaxError. Check your version withpython --version. - Expecting a bare name to compare:
case RED:does not compare with a variable calledRED. It captures the value into a new variable namedREDand always matches. Use a dotted name such asColor.REDor a literal. - Using
orinstead of|: writecase "a" | "b":. An OR pattern also cannot bind different variable names on each side. - Putting a catch-all case first: a capture pattern without a guard matches everything, and Python reports a
SyntaxErrorwhen it hides later cases. Placecase _:last. - Forgetting the wildcard: when nothing matches and there is no
case _:, the statement silently does nothing. - Wrong order of patterns: a general pattern before a specific one hides the specific one. Test
bool()beforeint(), and(0, 0)before(x, y). - Matching a string like a list: a string is never matched by a sequence pattern. Split it first, or compare it as a whole with a literal pattern.
- Expecting fall-through or needing break: only the first matching case runs, and Python leaves the statement at once. No
breakis needed.
Key Takeaways
matchcompares a value with patterns from top to bottom and runs only the firstcasethat matches.- The wildcard
_matches anything and is used as the final “none of the above” case. - Use
|to combine alternatives, and anifguard to add an extra condition to a case. - A plain variable name in a pattern captures a value. It does not compare with an existing variable.
- Sequence patterns take apart lists and tuples, mapping patterns take apart dictionaries, and class patterns check types and attributes.
- Strings are not matched as sequences, and mapping patterns ignore extra keys.
matchrequires Python 3.10 or later. For simple true/false decisions,if/elif/elseis still the right tool.
Frequently Asked Questions
What is the match case statement in Python?
The match statement compares a value with a series of patterns written as case blocks and runs the block of the first pattern that matches. It is called structural pattern matching and was added in Python 3.10. A pattern can be a simple literal or the shape of a list, a dictionary, or an object.
Which Python version supports match case?
Python 3.10 and later. In Python 3.9 and earlier, the match statement raises a SyntaxError, so use an if, elif, else chain instead.
Is match case the same as a switch statement?
It can be used like a switch statement to choose between several values, but it is more powerful. It also matches the structure of lists, tuples, dictionaries, and objects, captures parts of the data into variables, and supports guards. There is no fall-through, so no break statement is needed.
What does case _ mean in Python?
The underscore is the wildcard pattern. It matches any value and does not store it, so case _ works like the final else of an if chain. It should be the last case. If no case matches and there is no wildcard, the match statement does nothing.
How do I match multiple values in one case?
Join the alternatives with the vertical bar, for example case “Sat” | “Sun”:. This is an OR pattern. Do not use the keyword or inside a pattern, because it does not create an OR pattern.
What is a guard in a Python case statement?
A guard is an if condition placed after a pattern, as in case n if n < 0:. The case runs only when the pattern matches and the guard is true. If the guard is false, Python tries the next case.
Can match case work with dictionaries and classes?
Yes. A mapping pattern such as {“type”: “click”, “x”: x} matches a dictionary that contains those keys and captures the values, and it ignores extra keys. A class pattern such as Point(x=0, y=y) checks the type of an object and its attributes.
Should I use match case or if elif else?
Use if, elif, else for simple true or false conditions and ranges of numbers. Use match case when you compare one value with many literals, or when you need to take apart structured data such as lists, tuples, dictionaries, and objects while you test it.