About
Initialization and extraction of variables
Articles Related
List
Unpacking: A convenient way to initialize variables from a list
>>> [x,y] = [1, 2]
>>> x
1
>>> y
2
Sequence
Multiple assignment is really just a combination of tuple packing and sequence unpacking
Packing
Sequence packing: The values 12345, 54321 and 'hello!' are packed together in a tuple
t = 12345, 54321, 'hello!'
t
(12345, 54321, 'hello!')
Unpacking
The reverse packing operation
x, y, z = t
>>> x
12345
>>> y
54321
>>> z
'hello!'
Sequence unpacking works for any sequence on the right-hand side. Sequence unpacking requires the list of variables on the left to have the same number of elements as the length of the sequence.
Comprehension
>>> listoflists = [[1,1],[2,4],[3, 9]]
>>> [y for [x,y] in listoflists]
[1, 4, 9]