A Python feature in which elements of an iterable are simultaneously assigned to multiple variables, e.g. a, b, c = [1, 2, 3].
Iterable unpacking (sometimes known as 'tuple unpacking', although the concept applies equally to any iterable, not just tuples) is a feature of Python which allows for the assignment of the elements of an iterable to be assigned to multiple variables:
>>> a, b, c = [1, 2, 3]
>>> a
1
>>> b
2
>>> c
3
This feature can be used to swap the values of two variables without the use of a temporary 'holding' variable, as traditionally employed in other languages:
>>> a = 1
>>> b = 2
>>> a, b = b, a
>>> a
2
>>> b
1
>>> # rather than:
... a = 1
>>> b = 2
>>> temp = a
>>> a = b
>>> b = temp
>>> a
2
>>> b
1
If the number of elements in the iterable does not match the number of variables on the left hand side of the assignment, A ValueError
is raised:
>>> d, e = 4, 5, 6
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
>>> f, g, h = 7, 8
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack
Since Python 3, Extended iterable unpacking allows "spare" elements of the iterable to be assigned to a list (note the *
):
>>> x, *y, z = "kapow"
>>> x
'k'
>>> y
['a', 'p', 'o']
>>> z
'w'