How to unpack a Tuple or List in Python

Spread the love

You have a tuple or list or any iterable of N items and you want to unpack them into N variables.

Let’s say you have a tuple which contains 3 elements.

In [1]: data = (5, 10, 15)

And you want to assign 5 to a, 10 to b and 15 to c variables. One way of doing this is the following.

In [2]: a = data[0]

In [3]: b = data[1]

In [4]: c = data[2]

Here, we first access the element and then assign them into a variable. But you can see this is very verbose. A better way to perform this operation is the following.

In [5]: a, b, c = data

In [6]: a
Out[6]: 5

In [7]: b
Out[7]: 10

In [8]: c
Out[8]: 15

In just One line unpack all the elements of the tuple. Only requirement for unpacking a tuple or any iterable is that the number of items on the right hand side should match with the number of variables on the left hand side. If they do not match then python will throw an error.

In [9]: a, b, c, d = data
Traceback (most recent call last):

  File "C:\Users\BHOLA\AppData\Local\Temp\ipykernel_8964\3571094354.py", line 1, in <module>
    a, b, c, d = data

ValueError: not enough values to unpack (expected 4, got 3)

As I said before, you can unpack any iterable in python like this. Let’s unpack the characters of a string in this way.

In [10]: a, b, c, d, e, f = 'python'

In [11]: a
Out[11]: 'p'

In [12]: b
Out[12]: 'y'

In [13]: c
Out[13]: 't'

In [14]: d
Out[14]: 'h'

In [15]: e
Out[15]: 'o'

In [16]: f
Out[16]: 'n'

Rating: 1 out of 5.

Leave a Reply