User Tools

Site Tools


python3_unpacking

This is an old revision of the document!


Unpacking Sequences

Sequences can be explicitly/implicitly unpacked into discrete, ordered units of some type. Unpacking happens automatically using the , (comma). (The syntax is also used for Tuple construction.)

Unpacking works only in instances where the number of variables used exactly matches the number of items in the sequence.

In the below examples parenthesis are not required, and are included for clarity.

Implicit Unpacking: Member Assignment

The most common application of unpacking is to (shallow) copy items into named variables.

Lists

Unpacking a List.

>>> seq = [1, 2, 3]
>>> (a, b, c) = seq  # a=1, b=2, c=3

Tuples

Unpacking a Tuple.

>>> tup = ('a', 'b')
>>> (x, y) = tup # x='a', y='b'

Strings

Unpacking the characters of a String.

>>> (first, second, third) = "abc" # first='a', second='b', third='c'

In-Place Swap/Mutual Replacement

Swapping objects.

>>> x = 1
>>> y = 2
>>> (x, y) = (y, x) # x=2, y=1

Explicit Unpacking: The * (Star) Operator

The unary * (star) operator is used to explicitly indicate unpacking, often outside the context of assignment. Use is common when elements of a sequence are intended to be used as the parameters to a function.

E.g., (Assume that seq contains 3 elements) fun(seq[0], seq[1], seq[2]) could be rephrased more tersely as fun(*seq).

Unpacking Arguments

Consider printing values in a List.

>>> print([1, 2, 3]) # legal, but performs a cast str([1, 2, 3])
[1, 2, 3]

In many instances we may wish to print a list's elements, but not formatted as a Python3 list.

>>> print(*[1, 2, 3]) # as though we indexed each individually
1 2 3

Extended Iterable Unpacking

Extended Iterable Unpacking 1) extends unpacking to allow sequences on the left hand side of an assignment.

Like regular unpacking for member assignment, extended iterable unpacking is only allowed in instances where the Python3 interpreter can infer the number and position of arguments.

Unpacking First and Rest

>>> (first, *rest) = list(range(1, 10)) # first=0, rest=[1, 2, ..., 9]

Unpacking First, Rest, and Last

One or more additional named variables can be specified before or after the rest.

>>> (first, *rest, last) = list(range(1, 10)) # first=0, rest=[2, 3, ..., 8], last=9
1)
PEP 3132 - Extended Iterable Unpacking
python3_unpacking.1533570546.txt.gz ยท Last modified: 2018/08/06 10:49 by jguerin