Unpacking (a, b = …)
Unpacking lets you spread the items of a sequence into several names in a single line.
Used in 104 lessons of the course, from 00.01.
Unpacking assigns several values to several names at once. On the left of the = you write names separated by commas. On the right goes something with items: a tuple, a list, a string.
Python gives the first item to the first name, the second to the second, and so on. The number of names must match the number of items. If it doesn't, it fails, which protects you from unexpected data.
It is written this way because it is clearer than x = pair[0] and y = pair[1]: the names say what each piece is.
In the course you see it in definition, where = GLOSSARY[key]. There GLOSSARY[key] returns a tuple of two items and each one gets its own name. It also works in a for loop, to walk through pairs.
x, y = (1, 2)
Reach for it when: a tuple, a list or a returned value carries several pieces and you want a clear name for each one.
Examples
Common mistake
pair = ("a", "b", "c")
first, second = pair
print(first, second)Why: There are three items but only two names. Python does not silently drop any.
How to write it: Use as many names as items: first, second, third = pair.
