Skip to content
FollowtheDamnCode

Unpacking

Splitting sequences into names, with *rest.

3 minute read

Big idea

Unpacking pulls a sequence apart into names in one line. A starred name, *rest, scoops up whatever's left over.

The basics

You've done this already:

x, y = (3, 4)
a, b = b, a                 # swap
name, score = "Ada 88".split()

The number of names on the left must match the number of items on the right — or Python raises ValueError: too many values to unpack.

Starred unpacking

Put * before one name to collect "everything else" into a list:

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

head, *tail = "python"
print(head, tail)
What does it print? Show the answer
1
[2, 3, 4]
5
p ['y', 't', 'h', 'o', 'n']

Run and edit it in the app.

It works in loops too — handy for lines where the first word is a command and the rest are its arguments:

Commands with any number of arguments
lines = ["add milk eggs bread", "remove eggs", "clear"]
for line in lines:
    command, *args = line.split()
    print(command, args)
output
add ['milk', 'eggs', 'bread']
remove ['eggs']
clear []

Run and edit it in the app.

Ignoring values

By convention, _ is the name for a value you don't care about:

_, month, _ = "2026-10-03".split("-")
for _ in range(3):
    print("hip hip hooray")

Unpacking into new collections

* and ** also spread values into a new list or dict:

Merging lists and dicts
a = [1, 2]
b = [3, 4]
print([*a, *b, 5])

defaults = {"size": "M", "color": "blue"}
order = {"color": "red"}
print({**defaults, **order})
output
[1, 2, 3, 4, 5]
{'size': 'M', 'color': 'red'}

Run and edit it in the app.

When two dicts share a key, the later one wins — a neat way to apply settings over defaults. (defaults | order does the same since Python 3.9.)

Fix the bug: unpack the date into three parts
day, month = "03/10/2026".split("/")
print(day, month)
output
03 10

Run and edit it in the app.

The split makes three pieces but there are only two names — ValueError: too many values to unpack. Write day, month, _ = ... (or day, month, *_ = ...).

a, *b = [10, 20, 30]. What is b?

Watch it

Think of it like

Unpacking shopping bags at home: the milk goes in the fridge, the bread on the counter, and everything else in the cupboard.

Key terms

  • Unpacking — Assigning a sequence's items to several names at once.
  • Starred target — *rest, which collects the leftover items into a list.
  • _ — The conventional name for a value you're ignoring.

Check yourself

first, *rest = 'abc'. What is rest?

What does {**a, **b} do when both have the same key?

What is _ used for in for _ in range(3)?