Sub topic 5
Destructuring lists and tuples
This chapter assumes you know Python 3.10 or later, the basic match and case syntax, literal patterns, capture patterns, and * unpacking in assignments.
What a sequence pattern checks
A sequence pattern is written with square brackets or parentheses. It matches a subject only if two things are true:
- The subject is a sequence, such as a
list, atuple, or arange. - The subject has the length the pattern describes.
If both hold, each sub-pattern is matched against the element in the same position. A bare name in a sub-pattern captures that element.
def run(command):
match command.split():
case ["quit"]:
return "quit"
case ["go", direction]:
return f"go {direction}"
case ["drop", *items]:
return f"drop {len(items)} items"
case _:
return "unknown command"
print(run("go north")) # go north
print(run("drop a b c")) # drop 3 itemscommand.split() returns a list. In ["go", direction], the literal "go" must equal the first element, and direction captures the second. The pattern fails for ["go"] or ["go", "north", "fast"] because the length is wrong.
Star patterns
One starred name inside a sequence pattern accepts any number of elements, including zero. The captured elements always form a list, even when the subject is a tuple. Use *_ to accept elements without binding them.
def describe(seq):
match seq:
case []:
return "empty"
case [x]:
return f"one item: {x}"
case [first, *_, last]:
return f"from {first} to {last}"
print(describe([])) # empty
print(describe((7,))) # one item: 7
print(describe([1, 2, 3, 4])) # from 1 to 4A pattern may contain only one starred name. [*a, *b] is a syntax error because the split would be ambiguous.
Nesting and mixing pattern types
Sub-patterns can be any pattern, including other sequence patterns. This lets you take apart nested data in one step.
def length_class(segment):
match segment:
case ((x1, y1), (x2, y2)) if x1 == x2:
return f"vertical at x={x1}"
case ((_, y1), (_, y2)) if y1 == y2:
return f"horizontal at y={y1}"
case ((_, _), (_, _)):
return "diagonal"
case _:
return "not a segment"
print(length_class(((0, 0), (0, 5)))) # vertical at x=0
print(length_class(((1, 2), (4, 2)))) # horizontal at y=2
print(length_class("ab")) # not a segmentThe last call shows a rule that surprises people. A str is not matched by sequence patterns, even though it is iterable. The same applies to bytes and bytearray. This prevents "ab" from matching [a, b] by accident.
Common errors
- Expecting a list pattern to match any iterable. Generators, sets, and dictionaries are not sequences, so they never match. Convert first, for example
match list(items):. - Forgetting that length matters.
[x, y]does not match a three-element list. Add a starred case or a final_case. - Thinking
[a, b]and(a, b)differ. They are equivalent. Both match lists and tuples. Choose the style that reads best. - Capturing a name you meant to compare. In
[first, *rest],firstis a new variable, not a comparison with an existingfirst. Chapter 9 covers value patterns for comparison.
Exercise
Write a function ends(seq) that returns the first and last elements of a list as a tuple, returns (x, x) for a one-element list, and returns None for an empty list. Which patterns do you need?
Show answer
Use three cases: case []: return None, then case [x]: return (x, x), then case [first, *_, last]: return (first, last). The [x] case must come before the star case only for clarity, because [first, *_, last] needs at least two elements and never matches a single-element list.