Python - (Un)Packing

Card Puncher Data Processing


Initialization and extraction of variables


Unpacking: A convenient way to initialize variables from a list

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


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


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

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


The reverse packing operation

x, y, z = t
>>> x
>>> y
>>> z

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]

Discover More
Card Puncher Data Processing
Python - List

Lists are used to store a collection of different pieces of information in a sequence order of under a single variable name. A list can be used to implement a . A list is mutable whereas a tuple is not....
Card Puncher Data Processing
Python - Sequence (type)

The following data structure are sequence: Sequence objects may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two...
Card Puncher Data Processing
Python - Tuple

Tuples are: an ordered sequence of elements, just like lists. immutable so they can be elements of sets but they can contain mutable objects. A tuple consists of a number of values separated...
Card Puncher Data Processing
Python - Variable

in Python. A variable name must start with a letter and must exclude certain special symbols such as the dot (period). The underscore is allowed in a variable name. The variable being assigned to is...
Card Puncher Data Processing
Python - lambda functions

in Python. See The expression below yields a function object. The unnamed object behaves like a function object defined with lambda generates a function and returns it, while def generates a...

Share this page:
Follow us:
Task Runner