Python – Unpack Tuples

What is Tuple Unpacking?

Unpacking allows you to extract values from a tuple and assign them to multiple variables in a single line.

This is useful when you want to work with individual elements of a tuple directly.

Basic Tuple Unpacking

Example:

fruits = ("apple", "banana", "cherry")
a, b, c = fruits
print(a)
print(b)
print(c)

Output:

apple
banana
cherry

Explanation:
Each variable a, b, and c gets one value from the tuple.

Number of Variables Must Match Number of Items

If the count doesn’t match, Python will raise a ValueError.

Example:

fruits = ("apple", "banana", "cherry")
a, b = fruits  # ❌

Output:

ValueError: too many values to unpack (expected 2)

Using Asterisk (*) to Collect Remaining Items

You can use * to collect multiple remaining items into a list.

Example 1:

numbers = (1, 2, 3, 4, 5)
a, *b = numbers
print(a)
print(b)

Output:

1
[2, 3, 4, 5]

Example 2:

numbers = (1, 2, 3, 4, 5)
a, *b, c = numbers
print(a)
print(b)
print(c)

Output:

1
[2, 3, 4]
5

Unpacking in a Loop

You can use unpacking in loops when looping over a list of tuples.

Example:

pairs = [(1, 'one'), (2, 'two'), (3, 'three')]
for number, word in pairs:
   print(f"{number} is written as {word}")

Output:

1 is written as one
2 is written as two
3 is written as three

Use Case: Swapping Variables

Tuple unpacking is commonly used to swap variable values.

Example:

a = 5
b = 10
a, b = b, a
print(a, b)

Output:

10 5

Nested Tuple Unpacking

If tuples are nested, you can unpack them at multiple levels.

Example:

data = ("John", (25, "Engineer"))
name, (age, job) = data
print(name)
print(age)
print(job)

Output:

John
25
Engineer

Summary

FeatureSupported?
Basic unpacking✅ Yes
Variable count mismatch❌ Error
Using *✅ Yes
Loop unpacking✅ Yes
Swapping variables✅ Yes
Nested unpacking✅ Yes