Sub topic 2
Destructuring Lists and Tuples
Assume Python 3.10 or later, plus basic knowledge of functions, conditionals, lists, tuples, dictionaries, classes, and unpacking.
Destructuring Lists and Tuples
A sequence pattern checks both shape and length. Names in the pattern capture elements. A starred name captures the remaining elements.
def command(text):
match text.split():
case ["quit"]:
return "quit"
case ["go", direction]:
return f"go {direction}"
case ["drop", *items]:
return f"drop {len(items)} items"
case _:
return "unknown"
print(command("go north")) # go north
print(command("drop key map")) # drop 2The pattern ["go", direction] requires exactly two elements. The pattern ["drop", *items] accepts any number of elements after "drop".
Matching Dictionaries
A mapping pattern requires its listed keys but may ignore extra keys. Use **rest to capture those extra key-value pairs.
def handle(event):
match event:
case {"type": "click", "pos": (x, y)}:
return f"click at {x},{y}"
case {"type": "key", "key": key, **rest}:
return f"{key}, extras: {len(rest)}"
case _:
return "ignored"
print(handle({"type": "click", "pos": (3, 4)}))Nested patterns let one case destructure a tuple stored inside a dictionary.
Refining a Case with `if` Guards
A guard adds a Boolean condition after the pattern. The case succeeds only when both the pattern and the guard succeed.
def classify(value):
match value:
case int(n) if n < 0:
return "negative integer"
case int(n):
return "nonnegative integer"
case _:
return "other"Naming a Sub-Pattern with `as`
An as pattern captures the complete value matched by a sub-pattern.
def first_positive(values):
match values:
case [int(n) as first, *rest] if first > 0:
return first, rest
case _:
return NoneHere, first is the original integer, while n is its captured value. They are equal, but the pattern shows two useful names.
Comparing Against Constants and Enum Members
A dotted name is a value pattern. Python compares it with the subject. A bare name would capture instead, so use dotted names for constants.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
def color_name(color):
match color:
case Color.RED:
return "red"
case Color.GREEN:
return "green"
case _:
return "other"Exercise
What does case [first, *rest] bind when the subject is [10, 20, 30]?
Show answer
first is 10, and rest is [20, 30].