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:
a and b;pair, unpacked into x and y.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.