Python - (Un)Packing

> Procedural Languages > Python > Python - Grammar (Package | Module)

1 - About

Initialization and extraction of variables

Advertising

3 - List

Unpacking: A convenient way to initialize variables from a list

>>> [x,y] = [1, 2]
>>> x
1
>>> y
2

4 - Sequence

Multiple assignment is really just a combination of tuple packing and sequence unpacking

4.1 - Packing

Sequence packing: The values 12345, 54321 and 'hello!' are packed together in a tuple

t = 12345, 54321, 'hello!' 
t
(12345, 54321, 'hello!')

4.2 - 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.

Advertising

5 - Comprehension

>>> listoflists = [[1,1],[2,4],[3, 9]]
>>> [y for [x,y] in listoflists]
[1, 4, 9]