Unzipping tuple elements in Python

It is possible to unpack tuple elements in Python. You can do so by assigning tuple elements to multiple variables. For this, use the assignment operator (=). The variable count to the left side of the assignment operator should match the number of tuple elements. See coding example below.

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

You can also use the * operator to unpack the elements of a tuple, which assigns all the remaining elements of the tuple to a new tuple. Here’s an example:

first, *rest = my_tuple

You can also use the * operator to unpack elements in the front of the tuple, too. See below:

*front, last = my_tuple

These two approaches can be combined. An example is provided in the code snippet below.

first, *middle, last = my_tuple

For more on Python check out our Python documentation: https://www.supplychaindataanalytics.com/wiki-python-en/