Python tip 14: sequence unpacking
You can assign the individual elements of a sequence to multiple variables. This is known as sequence unpacking and it is handy in many situations.
>>> details = ['2018-10-25', 'car', 2346]
>>> purchase_date, vehicle, qty = details
>>> purchase_date
'2018-10-25'
>>> vehicle
'car'
>>> qty
2346
Here's how you can easily assign and swap multiple variables.
# multiple assignments
>>> num1, num2, num3 = 3.14, 42, -100
# swapping values
>>> num1, num2, num3 = num3, num1, num2
>>> print(f'{num1 = }\n{num2 = }\n{num3 = }')
num1 = -100
num2 = 3.14
num3 = 42
Unpacking isn't limited to mapping every element of the sequence. You can use a *
prefix to catch all the remaining values (if any is left) in a list
variable.
>>> values = ('first', 100, 200, 300, 'last')
>>> x, *y = values
>>> x
'first'
>>> y
[100, 200, 300, 'last']
>>> s1, *nums, s2 = values
>>> s1
'first'
>>> nums
[100, 200, 300]
>>> s2
'last'
See Unpacking with starred assignments for more examples and explanations.
Video demo:
See also my 100 Page Python Intro ebook.