Initialization and extraction of variables
Unpacking: A convenient way to initialize variables from a list
>>> [x,y] = [1, 2] >>> x 1 >>> y 2
Sequence packing: The values 12345, 54321 and 'hello!' are packed together in a tuple
t = 12345, 54321, 'hello!' t
(12345, 54321, 'hello!')
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.
>>> listoflists = [[1,1],[2,4],[3, 9]] >>> [y for [x,y] in listoflists] [1, 4, 9]