Unpacking & Star Expressions

Published by Brayan K

Unpacking is assigning the elements of an iterable to multiple variables at once — like a, b, c = [1, 2, 3] — and star expressions let one variable scoop up the rest.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Give every value a destination

Unpacking distributes values from an iterable into assignment targets. The targets describe a structure: each unstarred target needs one value, and nested targets unpack the value at that position. You can use a tuple, list or another iterable; the operation is not tied to a particular container.

record = ("Mira", (4, 7))
name, (completed, planned) = record
print(name)
print(completed, planned)

left, right = "OK"
print(left, right)

# ✅ Expected output:
# Mira
# 4 7
# O K

Without a star, each level needs exactly as many values as targets. If the data has fewer values, Python cannot invent the missing one. The error gives the number of values expected and received, and the line it points to is the assignment that failed; compare those counts with the targets on that line to find the level that fell short, and check the structure before adding defaults.

name, score, status = ("Mira", 8)
print(name, score, status)

# ✅ Expected error:
# ValueError: not enough values to unpack (expected 3, got 2)
name, score = ("Mira", 8)
status = "pending"
print(name, score, status)

# ✅ Expected output:
# Mira 8 pending

A fixed pair is introduced in Tuples. This lesson develops variable-length assignments and collection displays; *args & **kwargs owns how function definitions collect their arguments.

Let one star collect the remaining items

A starred assignment target receives a new list of the values left after the unstarred targets have been filled. Put it at the beginning, middle or end according to the record format. The result is a list even when the input was a tuple, and it can be empty.

for packet in [("Mira", 4, 7, "ready"), ("Noor", "empty")]:
    name, *scores, status = packet
    print(name, scores, status)
    print(type(scores).__name__)

*earlier, latest = (2, 5, 9)
print(earlier, latest)

# ✅ Expected output:
# Mira [4, 7] ready
# list
# Noor [] empty
# list
# [2, 5] 9

The star does not make required targets optional. A name and a final status still need two values, even if the middle list may be empty.

name, *scores, status = ["Mira"]
print(name, scores, status)

# ✅ Expected error:
# ValueError: not enough values to unpack (expected at least 2, got 1)

A single target list can contain only one star: otherwise there is no rule for splitting the spare values between the two collections. Separate nested target lists can each have their own star, but that describes nested input, not two ways to divide one flat sequence.

first, *middle, *last = [1, 2, 3, 4]
print(first, middle, last)

# ✅ Expected error:
# SyntaxError: multiple starred expressions in assignment
first, *middle, last = [1, 2, 3, 4]
print(first, middle, last)

# ✅ Expected output:
# 1 [2, 3] 4

Unpacking consumes an iterator

A list can be iterated again, but an iterator remembers how far it has progressed. Unpacking with a star consumes the remaining iterator to build its list. It is not a lazy view, so do not use this form on an endless stream or when collecting the whole stream would be too expensive.

readings = iter([3, 6, 9])
first, *rest = readings
print(first, rest)
print(list(readings))

# ✅ Expected output:
# 3 [6, 9]
# []

The mechanics of one-pass iterators and lazy production belong to Generators & Iterators Mastery. Here the important choice is whether you want to collect all remaining values now.

Spreading builds a collection instead of assigning targets

A star on the right side spreads values into a collection display. Unlike an assignment target list, a display can contain several starred iterables. It creates the outer collection while preserving references to the values it inserts; it does not recursively copy nested objects.

early = ["Ada", "Bo"]
late = ("Cy",)
queue = ["host", *early, *late]
print(queue)
print(early)

single = ["done"]
only, = single
print(only)

# ✅ Expected output:
# ['host', 'Ada', 'Bo', 'Cy']
# ['Ada', 'Bo']
# done

The comma makes only, an unpacking target list. Without it, only = single would assign the whole list. For the difference between copying an outer list and copying nested values, see Slicing Lists & Strings.

Dictionary keys, merged mappings and call keywords differ

Iterating a dictionary produces its keys in insertion order, not its values or key/value pairs. Choose values() or items() explicitly when those are what the targets represent.

record = {"name": "Mira", "score": 8}
first, second = record
print(first, second)
name, score = record.values()
print(name, score)
for key, value in record.items():
    print(key, value)

# ✅ Expected output:
# name score
# Mira 8
# name Mira
# score 8

Two stars in a dictionary display merge mappings: a later value replaces an earlier value with the same key. Two stars in a function call supply keyword arguments, where supplying the same keyword twice is an error. Merging first and making one call is different from making two keyword expansions in that call.

defaults = {"mode": "draft", "copies": 1}
overrides = {"mode": "final"}
settings = {**defaults, **overrides}
print(settings)
print(defaults)
print(dict(**settings))

# ✅ Expected output:
# {'mode': 'final', 'copies': 1}
# {'mode': 'draft', 'copies': 1}
# {'mode': 'final', 'copies': 1}
defaults = {"mode": "draft"}
overrides = {"mode": "final"}
print(dict(**defaults, **overrides))

# ✅ Expected error:
# TypeError: dict() got multiple values for keyword argument 'mode'

The merged settings example is the repair when overriding is intentional. Call expansion requires string keys; dictionary displays can use other hashable key types. The full calling rules are in *args & **kwargs, while Dictionaries in Python owns mapping operations.

Summarise the middle of a packet

Keep the name and status as fixed fields, then add only the numbers between them. Fill the starred target and the total expression. An empty middle should produce a zero total without a special case.

for packet in [("Mira", 3, 5, "ready"), ("Noor", "empty")]:
    name, ___, status = packet
    total = ___
    print(name, total, status)

# 👉 replace ___ with *readings
# 👉 replace ___ with sum(readings)

# ✅ Expected output:
# Mira 8 ready
# Noor 0 empty

Separate delivery labels from their contents

Each non-empty delivery record begins with a recipient, ends with a delivery status, and contains zero or more item labels between those fields. Reject records with fewer than two fields before unpacking. For the others, print the recipient, number of items and status, then combine all the item labels into one list in input order. Use the three records below to check both the empty and invalid cases.

records = [
    ("Mira", "book", "pen", "sent"),
    ("Noor", "waiting"),
    ("unfinished",),
]
all_items = []
for record in records:
    if len(record) < 2:
        print("invalid record")
        continue
    recipient, *items, status = record
    print(recipient, len(items), status)
    all_items.extend(items)
print(all_items)

# ✅ Expected output:
# Mira 2 sent
# Noor 0 waiting
# invalid record
# ['book', 'pen']

Practice quiz

What does this program print? first, *rest = (2, 4, 6) print(first, rest, type(rest).__name__)

  • 2 (4, 6) tuple
  • 2 [4, 6] list
  • [2] [4, 6] list
  • 2 4 6

Answer: 2 [4, 6] list. A starred assignment target receives a list.

What does this program print? first, *middle, last = [1, 2] print(first, middle, last)

  • 1 None 2
  • 1 () 2
  • ValueError
  • 1 [] 2

Answer: 1 [] 2. The two unstarred targets consume both values, leaving an empty list.

What does this program print? data = {"x": 4, "y": 9} a, b = data print(a, b)

  • x y
  • 4 9
  • ('x', 4) ('y', 9)
  • x 9

Answer: x y. A dictionary iterates over keys unless you explicitly request values or items.

What does this program print? items = iter([1, 2, 3]) first, *rest = items print(list(items))

  • [1, 2, 3]
  • [2, 3]
  • []
  • None

Answer: []. The star collected every remaining item from the iterator.

What does this program print? left = [1, 2] right = [3] print([0, *left, *right]) print(left)

  • [0, [1, 2], [3]] [1, 2]
  • [0, 1, 2, 3] [1, 2]
  • [0, 1, 2, 3] [0, 1, 2, 3]
  • SyntaxError

Answer: [0, 1, 2, 3] [1, 2]. Collection displays spread values without changing the original lists.

What does this program print? base = {"mode": "draft", "copies": 1} print({**base, "mode": "final"})

  • {'mode': 'draft', 'copies': 1}
  • TypeError
  • {'mode': ['draft', 'final'], 'copies': 1}
  • {'mode': 'final', 'copies': 1}

Answer: {'mode': 'final', 'copies': 1}. Later entries in a dictionary display replace earlier values for the same key.

What does this program print? only, = [7] whole = [7] print(only, whole)

  • 7 [7]
  • [7] [7]
  • 7 7
  • ValueError

Answer: 7 [7]. The comma requests unpacking; a lone name receives the whole assigned object.

Which operation rejects the input because two required fields are missing?

  • Collecting every item with one starred target
  • Merging two dictionaries with one shared key
  • Assigning three unstarred targets from a one-item list
  • Spreading two lists into a new list

Answer: Assigning three unstarred targets from a one-item list. Every unstarred assignment target needs one value; a mismatched shape raises ValueError.

Continue this course

Related lessons