Packing & Unpacking Tuples
In Python, you can group values together into a tuple without even typing parentheses (called Packing), and extract them into separate variables in a single line (called Unpacking).
Tuple Packing
When you assign multiple comma-separated values to a single variable name, Python automatically packs them into a tuple:
# Python automatically packs these into a tuple
user_info = "Alice", 25, "Engineer"
print(user_info) # Output: ('Alice', 25, 'Engineer')
print(type(user_info)) # Output: <class 'tuple'>
Tuple Unpacking
You can easily extract tuple values back into separate variables on the left side of the assignment sign =:
user_info = ("Alice", 25, "Engineer")
# Unpacking into 3 distinct variables
name, age, profession = user_info
print(name) # Output: Alice
print(age) # Output: 25
print(profession) # Output: Engineer
Swapping Variables Instantly
In most other programming languages, swapping the values of two variables requires creating a temporary third storage variable. In Python, tuple unpacking lets you swap values in a single line:
a = 10
b = 99
# Swap values cleanly in one line
a, b = b, a
print(f"a is now: {a}") # Output: a is now: 99
print(f"b is now: {b}") # Output: b is now: 10
Catching Leftover Items (*)
If your tuple has many items and you only care about the first few, use an asterisk * before a variable name to collect all leftover items into a list:
scores = (100, 95, 88, 72, 65, 50)
first, second, *remaining = scores
print(first) # Output: 100
print(second) # Output: 95
print(remaining) # Output: [88, 72, 65, 50]
- Variable Count Mismatch: Unpacking
data = (1, 2, 3)intox, y = dataraisesValueError: too many values to unpack. - Fix: Ensure variable count matches exactly, or use the
*operator (x, *rest = data) to catch remaining elements.
Quick Summary
- Tuple Packing: Combining multiple comma-separated values into a single tuple object (
point = 10, 20). - Tuple Unpacking: Assigning tuple elements directly into separate variables (
x, y = point). - Extended Star Unpacking (
*): Collects leftover elements into a dynamic list (first, *middle, last = items). - Clean Swapping: Swap two variables cleanly without temporary variables using
a, b = b, a.
What's Next?
Let's move to Module 10: Sets to discover how Python stores unique collections of unordered data without duplicate items!