Skip to main content

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]

Common Beginner Mistakes

Mismatched variable count during unpacking
# Wrong - trying to unpack 3 items into only 2 variables
data = ("red", "green", "blue")
color1, color2 = data # ValueError: too many values to unpack

# Right - ensure the number of variables matches, or use * to catch leftover items
color1, color2, color3 = data

What's Next?

Let's move to Module 10: Sets to discover how Python stores unique collections of unordered data without duplicate items.