a, *rest = t
Built-in Data Structures

Meaning

Unpacks an iterable into a first element and the remaining elements as a list. Useful when you need to separate the head from the tail of a sequence.

Primary Function

Sequence unpacking

Communicative Purpose

Extract the first item and the rest of items from an iterable for further processing.

Pattern

head, *tail = sequence

Core Structure

... , *... = ...

Função primária

Sequence unpacking

Propósito comunicativo

Extract the first item and the rest of items from an iterable for further processing.

Situações de gatilho

Data processing: handling the first element differently; Recursive algorithms: processing the head of a list before recursing on the tail; Functional pipelines: splitting a collection into head and tail for stepwise transformation

Contextos

Common in functional-style Python code, data processing pipelines, algorithm implementations (e.g., quicksort, linked list simulations), and when working with unknown-length sequences.

Padrão

head, *tail = sequence

Estrutura central

... , *... = ...

Slots de substituição

head: identifier, tail: identifier, sequence: iterable

Colocados típicos

  • used with for loops
  • recursion
  • slicing
  • list.head/tail patterns

Substituições comuns

  • head
  • *tail = seq
  • *initial
  • last = seq
  • *middle
  • = seq (to ignore)
  • a
  • b
  • *rest = t

Erros comuns

Using *rest on non-iterable, forgetting parentheses when unpacking nested structures, expecting *rest to be a tuple when it's a list, attempting to unpack when iterable length is less than required leading to ValueError.

Similar / contraste

Extended unpacking vs simple unpacking (a, b = t) – the latter expects exactly two items; vs slicing (head = t[0]; tail = t[1:]) – slicing creates a new list each time.

Interferências

Coming from languages like C or Java where there is no built-in unpacking; may mistakenly use index access or loops.

Família do chunk

  • sequence unpacking
  • iterable unpacking
  • destructuring assignment

Nuance

*rest always returns a list, even if zero elements; if the iterable is not a list or tuple, it still works as long as it's iterable; cannot be used with non-iterable objects like integers.

Efeito pragmático

Makes code concise and readable when separating head from tail; avoids manual indexing and slicing.

Dica de memória

Think 'head and the rest' when you see a comma followed by an asterisk.

Nota

Useful for recursive algorithms and functional-style processing; note that *rest always returns a list, even when empty, and can be combined with other unpacking patterns like *_, last = seq to ignore intermediate values.

Upgrade path

Nested unpacking: a, *b, c = seq; or using * to capture middle elements: *middle, = seq

Frequência: MediumFormulaicidade: Semi-fixedTipo de construção: unpacking assignmentPrioridade de aquisição: Recognition firstPrioridade de output: BothTag de espaçamento: Medium-term

Log in to save chunks.