Computer Science · Ch 10 — Tuples and Dictionaries
Tuple Assignment
10.4
Tuple Assignment
Tuple assignment (also called unpacking) is a very useful Python feature: a tuple of variables on the left side of the assignment operator receives, position by position, the corresponding values from a tuple on the right side. The first variable gets the first value, the second gets the second, and so on.
# 10 goes to a, 20 goes to b — in one statement
>>> (a, b) = (10, 20)
>>> print(a)
10
>>> print(b)
20
Unpacking a stored tuple
A tuple already held in a variable can be unpacked the same way — a natural fit for records:
>>> student = ('Nisha', 23, 'IP')
>>> (name, rollNo, subject) = student
>>> name
'Nisha'
>>> rollNo
23
>>> subject
'IP'
The counts must match
The number of variables on the left must be exactly the same as the number of elements in the tuple on the right; otherwise Python raises a ValueError:
>>> (w, x, y, z) = (5, 6, 8)
ValueError: not enough values to unpack (expected 4, got 3)
Expressions on the right are evaluated first
If the right side contains expressions, each expression is evaluated first, and only then are the results assigned to the variables on the left:
# 12 + 3 evaluates to 15, 20 + 5 evaluates to 25
>>> (p, q) = (12 + 3, 20 + 5) …