What is sequence unpacking in Python
What is Sequence Unpacking
We can perform several different assignments simultaneously.
x, y, z = 1, 2, 3
print x, y, z
The code above generates the following result.
We can use it to switch the contents of two (or more) variables:
x, y, z = 1, 2, 3
x, y = y, x
print x, y, z
The code above generates the following result.
Unpack from a tuple.
values = 1, 2, 3
print values
x, y, z = values
print x
The code above generates the following result.
This is particularly useful when a function or method returns a tuple or other sequence or iterable object.
To retrieve and remove an arbitrary key-value pair from a dictionary. You can then use the popitem method, which does just that, returning the pair as a tuple. Then you can unpack the returned tuple directly into two variables:
scoundrel = {'name': 'Robin', 'girlfriend': 'Marion'}
key, value = scoundrel.popitem()
print key
print value
The code above generates the following result.