Tuple Unpacking#
Note
Source: Python-specific — no direct equivalent in the C# edition.
The swap a, b = b, a replaces the three-variable swap used in the
C# sorting examples. zip() unpacking replaces paired index loops.
Tuple unpacking (also called destructuring) assigns each element of a tuple to a separate variable in one statement.
Basic Unpacking#
point = (3, 7)
x, y = point
print(x, y)
Output:
3 7
The number of variables on the left must match the number of elements
in the tuple (or you get a ValueError).
Swapping Variables#
The cleanest way to swap two variables in Python uses tuple unpacking:
a, b = 10, 20
a, b = b, a
print(a, b)
Output:
20 10
Python evaluates the right-hand side completely before assigning, so no temporary variable is needed. Compare this to the C# equivalent:
int t = a;
a = b;
b = t;
Unpacking Function Return Values#
A function can return multiple values as a tuple, and the caller can unpack them:
def min_max(nums):
return min(nums), max(nums)
lo, hi = min_max([3, 1, 4, 1, 5, 9])
print(lo, hi)
Output:
1 9
Unpacking in for Loops with zip()#
zip(a, b) pairs up elements from two sequences. Unpacking in the
for heading processes both at once:
names = ["Alice", "Bob", "Carol"]
scores = [88, 73, 95]
for name, score in zip(names, scores):
print(f"{name}: {score}")
Output:
Alice: 88
Bob: 73
Carol: 95
zip() stops at the shortest sequence. Use zip(strict=True) in
Python 3.10+ to raise an error if the sequences have different lengths.
Extended Unpacking#
A * prefix captures the “rest” of the sequence into a list:
first, *rest = [1, 2, 3, 4, 5]
print(first) # 1
print(rest) # [2, 3, 4, 5]
*body, last = [1, 2, 3, 4, 5]
print(body) # [1, 2, 3, 4]
print(last) # 5