Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python starred unpacking: allocate the middle and reject wrong arity

Last updated: 30 Sept 20264 min read
tutorial
BeginnerBy AITrove Editorial

Starred assignment collects the unmatched middle elements of an iterable into a new list.

Download Python source kit

Operation contract

The wire record has a version at the front and a checksum at the end. The starred target captures zero or more payload fields, even when the input was a tuple. This is useful when the envelope has fixed endpoints but variable payload length. The parser still checks the version, field count and checksum; unpacking alone says nothing about record validity. A two-field record produces an empty payload, which this contract rejects.

Failure and ownership boundary

Unpacking consumes the iterable. Passing a one-use stream can exhaust it before any later validation, and an unbounded stream can allocate an unbounded middle list. This fixture first restricts a concrete list or tuple to five fields. Python iterators: exhaustion and repeatable collection ownership and Python unpacking: keyword collisions and strict record pairing have different contracts.

Working program

python
def decode_envelope(fields):
    if type(fields) not in (list, tuple) or not 3 <= len(fields) <= 5:
        raise ValueError("bounded envelope")
    version, *payload, checksum = fields
    if version != "v1" or type(checksum) is not int or checksum != sum(len(part) for part in payload if type(part) is str):
        raise ValueError("envelope fields")
    if any(type(part) is not str or not part for part in payload):
        raise ValueError("nonempty text payload")
    return payload

print(decode_envelope(("v1", "DEL", "R41", 6)))
try:
    decode_envelope(("v1", 0))
except ValueError:
    print("short envelope rejected")
try:
    decode_envelope(("v1", "DEL", 2))
except ValueError:
    print("checksum rejected")

Output

Output
['DEL', 'R41']
short envelope rejected
checksum rejected

Costs and limits

For n accepted fields, starred unpacking takes O(n) time and O(n) middle-list storage. The five-field gate bounds both here. The sum expression is also linear in the payload text length; production formats should cap each field length before computing it.

Common Mistakes

  • The starred target is a list even when the input is a tuple.
  • Unpacking does not validate a wire format or bound an arbitrary iterator.

Connected lessons

Python unpacking: keyword collisions and strict record pairing, Python iterators: exhaustion and repeatable collection ownership, Python CSV ingestion: cap bytes, rows and fields before publication.

python
starred-unpacking
Storage details