Meaning
The pattern `x, *rest = t` performs iterable unpacking, assigning the first element of the iterable `t` to `x` and collecting all remaining elements into a list `rest`. It simplifies handling sequences of unknown length by separating a leading item from the rest. Use it when you need to process the first item specially while still retaining the remaining items for further iteration or processing.
Primary Function
Sequence unpacking
Communicative Purpose
Enables flexible handling of variable‑length iterables by separating the first element from the remainder
Pattern
first, *remaining = source
Core Structure
... , *... = ...
Função primária
Sequence unpacking
Propósito comunicativo
Enables flexible handling of variable‑length iterables by separating the first element from the remainder
Situações de gatilho
Data processing: extracting header from a list of values; API design: separating mandatory argument from optional ones; Algorithms: processing first node of a path while keeping the tail
Contextos
Python scripts, data analysis notebooks, web back‑ends that manipulate lists or tuples, command‑line utilities parsing arguments
Padrão
first, *remaining = source
Estrutura central
... , *... = ...
Slots de substituição
first: element from iterable, remaining: list of remaining elements, source: any iterable
Colocados típicos
- for loop
- function arguments
- list comprehension
- slicing
Substituições comuns
- Use slicing instead
- e.g. `first = seq[0]
- remaining = seq[1:]` – more verbose and creates a new list each time
Erros comuns
1. Omitting the star (`first, rest = seq`) leads to ValueError when lengths differ; 2. Assuming `rest` will be a tuple – it is always a list, which can cause type‑related bugs; 3. Using a mutable default for `rest` in function definitions, causing shared state across calls
Similar / contraste
Standard multiple assignment without star (`a, b = seq`) vs starred unpacking; tuple unpacking (`a, b, c = seq`) which requires exact length
Interferências
Coming from JavaScript: destructuring uses brackets `const [first, ...rest] = array;` – in Python the star appears on the left side of the assignment, not inside brackets
Família do chunk
- sequence unpacking
- iterable unpacking
- multiple assignment
Nuance
1. Do not use when you need all elements individually because `rest` groups them into a list; 2. Slight overhead of creating a new list for `rest`; 3. If the iterable is empty, a ValueError is raised for the missing first element
Efeito pragmático
Allows concise extraction of a leading element while preserving the rest for iteration, reducing boilerplate and potential off‑by‑one errors
Dica de memória
Starred unpacking is like taking the first slice of a pizza and putting the remaining slices into a basket for later serving
Nota
The variable receiving the starred part is always a list, even if the source iterable is a tuple
Log in to save chunks.