Tuple Packing and Unpacking
Tuple Packing
Tuple packing occurs when multiple values are assigned to a single variable, automatically creating a tuple.
python packed_data = 1, 'apple', 3.14 print(packed_data) # (1, 'apple', 3.14)
Tuple Unpacking
Unpacking allows you to assign the elements of a tuple (or any iterable) to multiple variables in a single line. The number of variables must match the number of elements in the tuple.
python date_info = (2024, 6, 20)
Unpack the tuple elements into three separate variables
year, month, day = date_info
print(f"Year: {year}, Month: {month}, Day: {day}")
Practical Use: Swapping Variables
Unpacking is the standard Pythonic way to swap two variable values without needing a temporary third variable.
python a = 10 b = 20
Swap a and b
a, b = b, a
print(f"a: {a}, b: {b}") # a: 20, b: 10
Arbitrary Unpacking (* operator)
If you want to extract a few specific items and capture the rest, use the asterisk (*) operator (often called the 'star expression').
python full_list = [10, 20, 30, 40, 50]
first, second, *rest = full_list
print(first) # 10 print(second) # 20 print(rest) # [30, 40, 50] (rest is always a list)