Write a Python program to unpack a tuple in several variables


The program is written in Python and performs the following steps:

  • A tuple a is defined with three integers, 4, 8, 3.
  • The value of a is printed to the console.
  • Three variables n1, n2, and n3 are defined and assigned the values from the tuple a using tuple unpacking.
  • The sum of the values of n1, n2, and n3 is calculated and printed to the console.
  • An attempt is made to unpack the tuple a into four variables n1, n2, n3, and n4. This will result in a ValueError because the number of variables does not match the number of items in the tuple.

In Python, tuple unpacking is a way to unpack the elements of a tuple into separate variables. In the program, the tuple a is unpacked into three variables n1, n2, and n3, which are then used to calculate the sum of the values. The program ends with an error because there are only three elements in the tuple a, but an attempt was made to unpack it into four variables.

Source Code

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

Output

(4, 8, 3)
15

Example Programs