Unpacking the items of tuples

In this section, we will learn how to unpack the tuple variable. Let's learn by example: 

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

In the preceding example, tuple's items have been assigned to a, b, and c variables correspondingly. 

What happens if you use more number of variables than the number of items in a tuple. Let's see more examples:

>>> tup2 = (5,6)
>>> x,y,z = tup2

Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
x,y,z = tup2
ValueError: need more than 2 values to unpack

So, interpreter throws a ValueError

What happens if you use less number of variables than the number of items in a tuple. Let's see more examples:

>>> tup2 = (5,6)
>>> x,y,z = tup2

Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
x,y,z = tup2
ValueError: need more than 2 values to unpack

So, the interpreter once again shows an error with a different description.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.226.255