Tuple Unpacking

tags: #python/documentation/tuples

Unpacking With Other Python Objects

Unpacking into multiple variable names also works with lists, or any other iterable objects, as long as there is exactly one value for each variable. For example, you can write x, y = [3, 4].

Python has a tuple assignment feature that allows a tuple of variables on the left of an assignment statement to be assigned values from a tuple on the right of the assignment.

Another way to think of this is that the tuple of values is unpacked into the variable names; why this is also referred to as unpacking of tuple

This allows you to assign more than one variable at a time when the left side is a sequence.

The process of assigning values to a tuple is known as packing. (see above examples)

This process of unpacking or tuple assignment assigns the values on the right-hand side to the left-hand side variables:

>>> (a, b, c) = (1, 2, 3)
>>> print(a, b, c)
1 2 3

In unpacking, we basically extract the values of the tuple into a single variable.

Each value is assigned to its respective variable.

All the expressions on the right side are evaluated before any of the assignments.

Variables MUST Equal to the len(Tuple)

The number of variables on the left and the number of values on the right have to be the same; i.e. make sure the number of values you are unpacking matches the number of variables being assigned.

(a, b, c, d) = (1, 2, 3)

This will return a ValueError: need more than 3 values to unpack.

Powered by Forestry.md