Tuple Unpacking in Python: a, b = pair
Tuple Unpacking: Many Variables in One Line
Unpacking means taking the items out of a tuple and putting each one into its own variable, all in one line.
person = ("Sunny", 25, "Pune")
name, age, city = person
print(name)
print(age)
print(city)Sunny 25 Pune
Think of it like unpacking a lunch box with three compartments onto three plates: the first compartment goes on the first plate, the second on the second, and so on.
The rules
- The variable names go on the left, separated by commas. The tuple goes on the right.
- The first name gets the first item, the second name gets the second item, and so on.
- The number of names must match the number of items.
- It works with lists too:
a, b = [1, 2].
Good: names instead of indexes
Without unpacking, you'd pick out every item by its index:
person = ("Sunny", 25)
name = person[0]
age = person[1]
print(name, "is", age)Sunny is 25
It works, but it's two lines, and person[1] doesn't say what's inside. Unpacking does both jobs at once, and the names explain the data:
person = ("Sunny", 25)
name, age = person
print(name, "is", age)Sunny is 25
Avoid: the wrong number of names
If the counts don't match, Python stops with a ValueError:
point = (3, 5, 9)
x, y = pointValueError: too many values to unpack (expected 2, got 3)
point = (3, 5)
x, y, z = pointValueError: not enough values to unpack (expected 3, got 2)
Read the message like a sentence: "I expected 2 names' worth of values, but I got 3." Count the names on the left, count the items on the right, and make them equal.
Common beginner doubt: "Does unpacking empty the tuple?" No! The tuple stays exactly as it was. The variables only get copies of its values, so you can still use person afterwards.
name, age = person: one name per item, in order.