w3resource logo


Python Exercises

Python Exercise: Unpack a tuple in several variables

Python tuple: Exercise-4 with Solution

Write a Python program to unpack a tuple in several variables.

Sample Solution :-

Python Code :

>>> #create a tuple
>>> tuplex = 4, 8, 3 
>>> print(tuplex)
>>> n1, n2, n3 = tuplex
>>> #unpack a tuple in variables
>>> print(n1 + n2 + n3) 
>>> #the number of variables must be equal to the number of items of the tuple
>>> n1, n2, n3, n4 = tuplex 

Output:

>>>
(4, 8, 3)
15
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 3 values to unpack
>>>

Python Code Editor:

#create a tuple
tuplex = 4, 8, 3
print(tuplex)
n1, n2, n3 = tuplex
#unpack a tuple in variables
print(n1 + n2 + n3)
#the number of variables must be equal to the number of items of the tuple
n1, n2, n3, n4 = tuplex

Improve this sample solution and post your code through Disqus.



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program