Python Tuples · Lesson 50 of 149

Python Extended Unpacking and Swapping

What you will learn

  • How a starred name (*rest) collects the extra items
  • The rules and errors of the star
  • Using * the other way: spreading items into lists, tuples and function calls
  • Merging dictionaries with **
  • Swap and rotate patterns

1. Collecting the rest

In lesson 8.2 the number of names had to match the items exactly. A name with a star in front takes all the items that are left over, so the counts no longer have to match:

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

*init, last = (1, 2, 3, 4)
print(init, last)

a, *mid, z = range(6)
print(a, mid, z)
1 [2, 3, 4]
[1, 2, 3] 4
0 [1, 2, 3, 4] 5
  • first, *rest splits off the first item.
  • *init, last splits off the last one.
  • a, *mid, z takes the first and last, and the star gets the middle.

The starred name always gets a list, even when you unpack a tuple, a string or a range. It may be an empty list:

a, *mid, z = [1, 2]
print(a, mid, z)

x, *y = [7]
print(x, y)

head, *tail = "hello"
print(head, tail)
1 [] 2
7 []
h ['e', 'l', 'l', 'o']
Quick check: what is `b` after `a, *b = (5,)`?

[], an empty list. There was nothing left over.

2. The rules of the star

Rule Example
At most one starred name per assignment *a, *b = [1, 2] is a SyntaxError: multiple starred expressions in assignment
The star collects into a list first, *rest = (1, 2, 3) gives rest = [2, 3]
The other names must still get an item each a, b, *c = [1] fails
Works for any collection you can loop over strings, ranges, sets, dictionaries (keys)

When there are too few items for the plain names, the message says "at least":

a, b, *c = [1]
ValueError: not enough values to unpack (expected at least 2, got 1)

To take the ends and ignore the middle, call it *_:

a, *_ = (1, 2, 3)
print(a)

*_, tail_item = (1, 2, 3)
print(tail_item)
1
3

3. Where the star is useful

A record with a variable tail. A name and any number of scores:

name, *scores = ["Rina", 90, 85, 77]
print(name, scores, sum(scores) / len(scores))
Rina [90, 85, 77] 84.0

A command and its arguments:

line = "cmd arg1 arg2 arg3"
cmd, *args = line.split()
print(cmd, args)
cmd ['arg1', 'arg2', 'arg3']

Rows of different lengths:

for row in [(1, 2, 3), (4, 5)]:
    f, *r = row
    print(f, r, end="; ")
print()
1 [2, 3]; 4 [5]; 

The biggest, the smallest and the middle of sorted data:

first, *middle, last = sorted([5, 3, 9, 1, 7])
print(first, middle, last)
1 [3, 5, 7] 9

Splitting a CSV-like line (the file chapter is 15):

head, *body, foot = "a,b,c,d".split(",")
print(head, body, foot)
a ['b', 'c'] d

A recursive sum (recursion is lesson 11.6): the head plus the sum of the rest:

def rec_sum(nums):
    if not nums:
        return 0
    h, *t = nums
    return h + rec_sum(t)

print(rec_sum([1, 2, 3, 4]))
10

4. The star the other way: spreading

On the right-hand side, a star spreads a collection into separate items. You can build a new list, tuple or set from several collections in one expression:

a = [1, 2]
b = (3, 4)
print([*a, *b])
print((*a, *b))
print([*a, 99, *b])
print({*a, *b})
print([*"ab", *range(2)])
[1, 2, 3, 4]
(1, 2, 3, 4)
[1, 2, 99, 3, 4]
{1, 2, 3, 4}
['a', 'b', 0, 1]

This is neater than a + list(b), because the collections may be of different types, and you can mix single items in between.

Spreading into a function call

A star in a call turns a collection into separate arguments (function arguments are chapter 11):

def total(a, b, c):
    return a + b + c

print(total(*[1, 2, 3]))
print(total(*(4, 5), 6))
print(list(range(*[2, 8])))
print(max(*[3, 9, 4]))
6
15
[2, 3, 4, 5, 6, 7]
9

print itself uses it, to show a list's items with a separator:

print(*[1, 2, 3])
print(*["x", "y"], sep="-")
1 2 3
x-y

Merging dictionaries with **

Two stars spread a dictionary into another dictionary. For repeated keys, the later one wins:

d1 = {"a": 1, "b": 2}
d2 = {"b": 20, "c": 3}
print({**d1, **d2})
print({**d1, "z": 0})
{'a': 1, 'b': 20, 'c': 3}
{'a': 1, 'b': 2, 'z': 0}

In Python 3.9 and later, the | operator does the same merge: d1 | d2. (Dictionaries are chapter 9.)

5. Swap and rotate patterns

The right side is worked out first, so unpacking swaps and rotates without a temporary name:

a, b, c = 1, 2, 3
a, b, c = c, a, b
print(a, b, c)
3 1 2

Each name takes the value from its neighbour: this rotates the three values. Swapping two list items in place:

lst = [1, 2, 3, 4, 5]
lst[0], lst[-1] = lst[-1], lst[0]
print(lst)
[5, 2, 3, 4, 1]

And a swap that depends on the old values, such as x becomes y, y becomes the sum:

x, y = 5, 10
x, y = y, x + y
print(x, y)
10 15

Without unpacking, a swap needs a temporary name:

a, b = 1, 3
tmp = a
a = b
b = tmp
print(a, b)
3 1

The unpacking form a, b = b, a is shorter and the usual Python style.

Worked example: the best and the rest

Rank players by name length (a made-up rule) and pick the winner and the others.

words = ["apple", "banana", "cherry"]
best, *others = sorted(words, key=len, reverse=True)
print(best, others)

podium = ["gold", "silver", "bronze"]
everyone = [*podium, "4th", "5th"]
print(everyone)
banana ['cherry', 'apple']
['gold', 'silver', 'bronze', '4th', '5th']
Step What happens
sorted(..., key=len, reverse=True) longest first; banana and cherry tie, and the sort is stable (lesson 7.4)
best, *others = ... the first goes to best, the rest into a list
[*podium, "4th", "5th"] spreads podium and adds two more items

The words and places are made up for the example.

Common mistakes

  • Using two starred names in one assignment.
  • Expecting the starred name to be a tuple. It is always a list.
  • Forgetting that the plain names still need items.
  • Confusing the two stars: *rest on the left collects; *items on the right spreads.
  • Using ** to merge when a key repeats, and forgetting that the later dictionary wins.

Key takeaways

  • A starred name in an assignment collects the extra items into a list (possibly empty); only one star is allowed.
  • Use first, *rest, *init, last and a, *middle, z to split sequences of any length.
  • On the right side, * spreads a collection into a list, tuple, set or function call; ** spreads a dictionary.
  • {**d1, **d2} merges dictionaries, and the later one wins.
  • a, b = b, a swaps, and a, b, c = c, a, b rotates, with no temporary name.

Practice

1. What are a and b after a, *b = "xyz"?

Show answer

a is "x" and b is ["y", "z"].

2. Get the first and the last item of [10, 20, 30, 40] into two names.

Show answer

first, *_, last = [10, 20, 30, 40] gives first = 10 and last = 40.

3. What does [*[1, 2], *(3,)] give?

Show answer

[1, 2, 3].

4. Why does a, *b, *c = [1, 2, 3] fail?

Show answer

Only one starred name is allowed in an assignment, so it is a SyntaxError.

5. Merge {"x": 1} and {"x": 5, "y": 2} so that the second one wins.

Show answer

{**{"x": 1}, **{"x": 5, "y": 2}} gives {'x': 5, 'y': 2}.

6. Rotate a, b, c = 1, 2, 3 so that a is 2, b is 3 and c is 1.

Show answer

a, b, c = b, c, a.