Sub topic 5
Destructuring lists and tuples
This chapter covers sequence patterns, the patterns that take apart lists and tuples inside a case. It assumes you know the earlier chapters on literal patterns, capture patterns and the _ wildcard. It also assumes Python 3.10 or later, and that you are comfortable with * unpacking in ordinary assignments such as first, *rest = items.
What a sequence pattern is
A sequence pattern looks like a list or tuple display. Python checks that the subject is a sequence of the right length, then matches each element against the sub-pattern in the same position. Any name in the pattern is bound to the matching element.
def describe(point):
match point:
case (0, 0):
return "origin"
case (x, 0):
return f"on the x-axis at {x}"
case (0, y):
return f"on the y-axis at {y}"
case (x, y):
return f"point {x},{y}"
case _:
return "not a 2D point"
print(describe((3, 0))) # on the x-axis at 3
print(describe([0, 7])) # on the y-axis at 7
print(describe((1, 2, 3))) # not a 2D pointThree things to notice in this example:
(0, 0)mixes two literal patterns. Both elements must equal0.(x, 0)mixes a capture pattern and a literal. The first element is bound tox, and the second must equal0.[0, 7]matches the pattern(0, y)even though the pattern is written with parentheses. A pattern written with(...)or[...]accepts a list or a tuple.
Brackets, parentheses, and bare commas
These three patterns are equivalent:
match pair:
case [a, b]:
...
case (a, b):
...
case a, b:
...The choice is style only. The shape of the pattern does not need to match the type of the subject. Python does not ask "is this a tuple?" when you write (a, b). It asks "is this a sequence with exactly two elements?"
There is one trap with single-element patterns. (x) is not a sequence pattern. Parentheses around a single pattern only group it, so (x) is the same as the capture pattern x, and it matches anything. To match a one-element sequence, write [x] or (x,).
Which subjects count as sequences
Sequence patterns match built-in sequence types such as list, tuple, range, collections.deque, and array.array. User classes also match if they are registered as collections.abc.Sequence subclasses.
Some objects never match, even though you can loop over them:
| Subject | Matches a sequence pattern? | Reason |
|---|---|---|
| `[1, 2]`, `(1, 2)` | Yes | Lists and tuples are sequences. |
| `range(3)` | Yes | `range` is a sequence type. |
| `"ab"`, `b"ab"`, `bytearray(b"ab")` | No | Python excludes `str`, `bytes` and `bytearray` on purpose. |
| `{1, 2}` | No | Sets have no order and no indexing. |
| `{"a": 1}` | No | Mappings have their own pattern type. |
| `iter([1, 2])`, generators | No | Iterators cannot be indexed or measured without consuming them. |
The string exclusion matters because a string such as "ab" would otherwise match [a, b], and code that expects a list of two items would silently accept text. If you want to destructure an iterator or a set, convert it first with list() or tuple().
def kind(value):
match value:
case [a, b]:
return f"pair {a!r}, {b!r}"
case _:
return "no match"
print(kind([1, 2])) # pair 1, 2
print(kind("ab")) # no match
print(kind(iter([1, 2]))) # no match
print(kind(list(iter([1, 2])))) # pair 1, 2Length and the star pattern
Without a star, a sequence pattern matches only a sequence of exactly the same length. [a, b] rejects a three-element list and also rejects a one-element list.
A star pattern such as *rest absorbs any number of leftover elements, including zero. It works like * in an assignment, with these rules:
- A pattern may contain at most one starred element.
- The star can sit at the start, in the middle, or at the end.
- The captured value is always a
list, even when the subject is a tuple. - Use
*_when you need to allow extra elements but do not need them.
The command parser below uses all of these ideas:
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 items
print(run("drop")) # drop 0 items
print(run("go")) # unknown command"drop" alone still matches ["drop", *items], because the star may capture zero elements. "go" alone falls through to _, because ["go", direction] needs exactly two elements.
A star in the middle lets you pick out both ends:
def summarize(values):
match values:
case []:
return "empty"
case [only]:
return f"one item: {only}"
case [first, *_, last]:
return f"first={first}, last={last}"
print(summarize([])) # empty
print(summarize((9,))) # one item: 9
print(summarize([1, 2, 3, 4])) # first=1, last=4
print(summarize((5, 6))) # first=5, last=6The order of the cases matters here. [first, *_, last] needs at least two elements. Because the one-element case comes first, a one-element sequence never reaches it.
The following check confirms that a star capture is always a list:
match (1, 2, 3):
case (head, *rest):
print(head, rest) # 1 [2, 3]Nested patterns
Each position in a sequence pattern can hold any pattern, including another sequence pattern. This lets you describe a whole shape in one line.
def segment_length(segment):
match segment:
case [(x1, y1), (x2, y2)]:
return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
case _:
raise ValueError("expected two points")
print(segment_length(((0, 0), (3, 4)))) # 5.0
print(segment_length([[1, 1], [1, 4]])) # 3.0The outer pattern requires exactly two items. Each item must itself be a two-element sequence. If any level has the wrong shape, the whole case fails and Python tries the next one.
You can mix nesting with literals, so a fixed tag can select a record type:
def price(order):
match order:
case ["coffee", ("small" | "medium") as size, qty]:
return qty * 2
case ["coffee", "large", qty]:
return qty * 3
case ["tea", _, qty]:
return qty * 2
case _:
return None
print(price(["coffee", "large", 2])) # 6
print(price(("tea", "green", 3))) # 6
print(price(["juice", "apple", 1])) # NoneThe first case uses an or-pattern and an as pattern, which later chapters cover in detail. Here size is bound but unused, so you could drop the as size part.
How a sequence pattern is checked
Python applies the same sequence of tests to every sequence pattern.
The subject expression after match is evaluated once, and the tests run for each case from top to bottom until one succeeds. Elements are tested left to right.
Common errors
Matching text by accident. match "go" with case [a, b] does not match, even though the string has two characters. If the input might be a string, split it first, as the command parser does with command.split().
Forgetting the trailing comma. case (x): is a capture pattern. Write case (x,): or case [x]: for a one-element sequence.
Using two stars. case [*a, *b]: is a syntax error. Only one star can appear in a sequence pattern, because two would make the split ambiguous.
Expecting a tuple from *rest. The captured value is a list. If you need a tuple, convert it with tuple(rest).
Relying on bindings after a failed case. Names are bound as the elements are matched. If a later element fails, earlier names may already hold values, even though the case did not run. Only use names inside the body of the case that matched.
match [5, 2]:
case [a, 1]:
print("first case")
case [_, b]:
print("second case", b) # second case 2Matching infinite or one-shot iterables. Because iterators are not sequences, they never match. Convert them to a list first, and only do so when the input is finite.
Choosing between sequence patterns and unpacking
A plain assignment such as x, y = point raises ValueError if the length is wrong. A sequence pattern lets you handle that case as a normal branch, so you can use it when the shape of the data varies. For data that always has the same shape, ordinary unpacking is shorter and clearer.
Exercise
Write a function ends(items) that takes a list or tuple and returns "empty" for an empty sequence, the single element for a one-element sequence, and a tuple (first, last) for anything longer. Which case order do you need, and what does ends("ab") return?
Show answer
def ends(items):
match items:
case []:
return "empty"
case [only]:
return only
case [first, _, last]:
return (first, last)
The empty and one-element cases must come before `[first, _, last], which needs at least two elements. ends("ab") returns None`, because a string is not matched by any sequence pattern and no case matches, so the function falls off the end.
Exercise
What does this code print, and why? match (1, 2, 3): case (a, b): print("two") case (a, *rest): print(a, rest)
Show answer
It prints 1 [2, 3]. The first case requires exactly two elements, so it fails on a three-element tuple. The second case binds a to 1 and rest to the list [2, 3]. The captured rest is a list even though the subject is a tuple.
Exercise
A teammate writes case (name): hoping to match a one-element tuple and bind its content to name. What actually happens, and how do you fix it?
Show answer
(name) is a group pattern around a capture pattern, so it is the same as case name:. It matches any subject and binds the whole subject to name. Fix it with case (name,): or case [name]:.