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.

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.

>>> (fst, snd, thd) = "abc" # fst='a', snd='b', thd='c'

In-Place Swap/Mutual Replacement

Swapping objects.

>>> x = 1
>>> y = 2
>>> (x, y) = (y, x) # x=2, y=1
python3_unpacking.1533567473.txt.gz ยท Last modified: 2018/08/06 09:57 by jguerin