Unpacking and Swapping
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Unpacking copies the items of a tuple into separate names in one line. It also gives a clean swap and a way to split a first item from the rest.
Unpacking into names
Unpacking means copying the items of a tuple or list into separate names in one statement, such as x, y = point. It works from left to right and needs one name for each item.
Reading a record with order[0] and order[1] hides what each part means. Unpacking gives every value its own name in one line.
order = ("Laptop", 2, 450)name, qty, price = orderprint(name)print(qty * price)Example 1 · Splitting an order line
line = ("Mouse", 3, 15.5)item, qty, price = linetotal = qty * priceprint(f"{item}: {total}")Mouse: 46.5
What this code does
- One line gives three clear names.
qty * priceis 3 times 15.5.- The f-string puts the item name and the total in one line.
Python fills the names from left to right: the first value goes to name, the second to qty, the third to price. The number of names must match the number of values, or Python raises a ValueError.
Swapping two values
In many languages a swap needs a third, temporary name. Python builds a tuple from the right side first, then unpacks it into the names on the left.
low = 90high = 40low, high = high, lowprint(low, high)a, b, c = 1, 2, 3a, b, c = c, a, bprint(a, b, c)Example 2 · Swapping two scores
first_try = 55second_try = 70first_try, second_try = second_try, first_tryprint(first_try)print(second_try)70 55
What this code does
- The right side is built from the old values first.
- Then both names are set at once, so no temporary name is needed.
The right side (high, low) is made from the old values before any name changes, so nothing is lost. The commas make the tuple; brackets are optional. Writing point = 3, 4 also builds a tuple.
Collecting the rest with *
Starred name is a name with * in front, such as *rest, used in unpacking. It collects all the values not taken by the other names into a new list. Only one is allowed.
Sometimes you want the first value and everything else, without counting the rest. A name with a star takes all the remaining values.
scores = (88, 92, 75, 60, 95)first, *rest = scoresprint(first)print(rest)*start, last = scoresprint(start, last)first, *middle, last = scoresprint(middle)Example 3 · Head and rest of a list
queue = ["T-1", "T-2", "T-3", "T-4"]current, *waiting = queueprint(current)print(waiting)print(len(waiting))T-1 ['T-2', 'T-3', 'T-4'] 3
What this code does
currenttakes the first ticket.waitingis a list of all the others.- Unpacking works on lists as well as tuples.
The starred name always gets a list, even when it gets one item or none. Only one starred name is allowed in a statement.
Ignoring values with _
Sometimes one part of a record is not needed. By habit, the name _ marks a value you will not use.
record = ("Ravi", "Delhi", 31)name, _, age = recordprint(name, age)for x, y in [(1, 2), (3, 4)]: print(x + y)_ is an ordinary name; it only tells the reader that the value is ignored. A for loop can unpack each item too, so x, y takes the two parts of every pair.
Next step
Check your understanding
10 quick questions