Skip to main content
A sequence pattern is a structural pattern matching construct introduced in Python 3.10 that unpacks and matches a subject against a sequence of sub-patterns. It verifies that the subject is an instance of collections.abc.Sequence and that its elements satisfy the specified positional sub-patterns. Notably, sequence patterns explicitly exclude str, bytes, and bytearray objects to prevent unintended character-level or byte-level unpacking.

Syntax and Equivalence

Sequence patterns can be defined using either square brackets [] or parentheses (). At the compiler level, both syntaxes are evaluated identically; [a, b] and (a, b) represent the exact same pattern.

Length and Element Matching

By default, a sequence pattern enforces a strict length check. The subject sequence must contain the exact number of elements as the sub-patterns defined in the case clause. Each element in the subject is then evaluated against the corresponding sub-pattern from left to right.

Variable-Length Matching (Starred Expressions)

To match sequences of arbitrary lengths, sequence patterns support a single starred expression (*), similar to iterable unpacking. The starred name binds to a list containing all remaining elements that are not matched by the positional sub-patterns.

Nested Sub-patterns

Sequence patterns are recursive. The sub-patterns within the sequence can be literal patterns, capture patterns, type patterns, or other structural patterns (including nested sequence or mapping patterns).

Binding the Entire Sequence

The as pattern can be combined with a sequence pattern to capture the entire matched sequence object into a variable, while simultaneously unpacking its elements.
Tired of Poor Python Skills? Fix That With Deep Grasping!Learn More