← All lessons

Unpacking

Sign in · Sign up

Lesson 5.15

A collection can be spread over variables — variables on the left, the collection on the right:

a, b = 1, 2
print(a, b)    # 1 2

a, b = b, a    # swap the values
print(a, b)    # 2 1

point = (3, 5)
x, y = point   # a tuple unpacks too

There is one rule: the number on the left and on the right must match. a, b = [1, 2, 3] raises a ValueError.

The two numbers first and second are set by the check. Print, in order:

  1. the numbers as they are — by unpacking into a and b;
  2. them after the swap;
  3. the first and the second of the list pair, unpacked into x and y.
Hint

Unpacking is several names on the left separated by commas: a, b = 1, 2.

In Python a swap is written without a third variable: a, b = b, a. The list pair unpacks the same way, only there is a list variable on the right.

Each point is one line of output. Two numbers are printed with one print with a comma: print(a, b) gives 1 2, while print(a) and print(b) give two lines.