How To Unpack Iterable/Sequence Objects into Multiple Variables in Python

How_To_Unpack_Iterable_Sequence_Objects_into_Multiple_Variables_in_Python

You may be familiar with packing separate variables into sequence objects. For example, creating two variables named a and b, and then create a new tuple t equals to (a , b).

In this post, you will learn to do the opposite, which is unpacking sequence objects into multiples variables.

How does unpacking a tuple/sequence work in Python

Python allows you to unpack a tuple or sequence containing n elements into n variables. This means that every element’s reference in the sequence object will be associated to a separate variable.

As you know, Python does not store values into variables. Instead, the value of a variable is an identifier that tells Python interpreter where the data associated with that variable is stored in memory.

Therefore, when we unpack a sequence object, such as a tuple, we assign the reference/identifier of each element to a separate variable.

If the current element is a value the Python assigns the reference of this value to the current variable. If the current element is variable, then it will assign the identifier associated to it to the current variable.

How to unpack a tuple or list object in Python

Now, let’s demonstrate what we discuss above using the following example.

>>> l = [321]
>>> x , y = ( 2 , l )

>>> id(2)
270154000

>>> id(x)
270154000

>>> id(l)
60473992

>>> id(y)
60473992

>>> y[0] = 2

>>> l
[2]

>>>

In this example, we created a list object l that equals to [321] and then we unpacked the tuple (2,l) into the two variables x and y.

As shown in the example, x took identifier of the value 2, which is 270154000. And, y took the identifier of l, which is 60473992.

Since 2 is an immutable object, modifying the value of x will not change the value of the object referenced by the identifier 270154000. Instead, doing this will create a new object.

However, modifying the value of y will change the value of the object referenced by the identifier 60473992, as shown in the listing above. This due to the fact that lists are mutable objects.

Unpacking other iterable objects into multiple variables

Python allows you to unpack, into variables using a simple assignment statement, any type of sequence object such as tuple and lists. In general, you can unpack any iterable object such set, strings, dictionaries and so on.

Unpacking a dictionary object into multiple variables

When unpacking a dictionary object, Python just assign each key to its associated variable in the assignment operation. For example:

>>> x,y={2:6,1:10}

>>> x
2

>>> y
10

 

The keys 2 and 1 have been assigned to x and y, respectively.

Unpacking a set object into multiple variables

When unpacking a set object, Python just assign each element in the set to its associated variable in the assignment operation. For example:

>>> x,y={2,1}

>>> x
2

>>> y
1

The elements 2 and 1 have been assigned to x and y, respectively.

Unpacking a string into multiple variables

When unpacking a string, Python just assign each character in the string to its associated variable in the assignment operation. For example:

>>> x,y='hi'

>>> x
'h'

>>> y
'i'

>>>

The characters ‘h’ and ‘i’ have been assigned to x and y, respectively.

Notice that the first character is assigned to the first variable and the second character is assigned to the second variable. This is the same behavior as for unpacking sequence objects.

What if the number of variables is less than the size of the iterable object?

Let’s take a look at the following example:

>>> a=2

>>> l=[321]

>>> x,y=(a,l)

Notice in the example that the number of variables match the size of iterable object. So, if the iterable object’s size is 2, then you will need 2 variables to upack this object, and vice versa.

Alternatively, if you, for example, use one variable instead of two variables then Python will raise the ValueError exception.

Python will display a message along with the type of exception, which will inform you that there is mismatch on the number of the values to unpack. Specifically, Python will tell that the sequence has more values that variables you supply.

>>> a,b=(2,3,5)

Traceback (most recent call last):
File "<console>", line 1, in <module>
ValueError: too many values to unpack (expected 2)

What if you use a variable many times in the assignment statement?

When unpacking some iterable object, you may sometimes – by mistake, use the same variable multiple times. So, how Python will behave in such situation?

To answer this question, let’s consider this example:

>>> a, b, a = (2,3,4)

>>> a
4

 

As you can see, we used the variable “a” two times in this listing. And the variable just simply conserve the last value assigned to it, which 4 in this case.

What to do when the number of variables is less than the size of the iterable/sequence to unpack?

In such situations, you may want to extract the value of the first element, last element, or the values of both elements of the sequence object. Also, you may want to extract all the elements except the first, the last, or both of them.

These are the only cases when you can unpack a sequence object into many variables, and the number of variables is less than the size of the unpacked object.

Note: This idea has a sense if you are dealing with a sequence object only. For a non-sequence object like a dictionary object, the concept of first/last element is not logical. Therefore, speaking of the last/first item does not make sense as you can see in the examples below.

How to unpack the first item in a sequence object (list, tuple, str)

To extract the first item of a sequence object, we use two variables. The first one stores the item in the head of the object and the second one stores the remaining items in the object, as shown in the example below:

>>> a,*b=[2,5,9,6,9,8]

>>> a
2

>>> b
[5, 9, 6, 9, 8]

>>>

The variable “a” has the value of the first element in the list, and the “b” variable memorizes the all the list’s elements except the item in the head.

How to unpack the last item in a sequence object

To extract the last element of a sequence object, we use two variables. The first one stores the items from the beginning of the object till the item before its end, and the second one stores the last item in the object, as shown in the example below:

>>> *b,a=[2,5,9,6,9,8]

>>> a
8

>>> b
[2, 5, 9, 6, 9]

>>>

The variable “a” has the value of the last element in the list, and the “b” variable memorizes the all the list’s elements except the item at the end of the list.

How to unpack items between the first item and the last item in a sequence object

First of all, you can use the code in this section to extract also the first/last item is a sequence object.

To extract the elements between the first item and the last item of a sequence object, exclusively, we use three variables.

The first one stores the item in the head of the object, the second one stores the items between the beginning and the end of the object, and the third variable stores the last item in the object, as shown in the example below:

>>> a,*b,c=[2,5,9,6,9,8]

>>> a
2

>>> b
[5, 9, 6, 9]

>>> c
8

>>>

The variable “a” has the value of the first element in the list, the “c” variable has the value of the last element, the “b” variable memorizes the all the list’s elements, except the items in the head and the tail of the list.

As a final note, you can use the techniques above if you know the location of the fields you want to unpack, and at the same time, you don’t know the size of the sequence object.

Leave a Reply

Your email address will not be published. Required fields are marked *


CAPTCHA Image
Reload Image