w3resource

Python Exercise: Unpack a tuple in several variables


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

Sample Solution:

Python Code:

# Create a tuple containing three numbers
tuplex = 4, 8, 3
# Print the contents of the 'tuplex' tuple
print(tuplex)

# Unpack the values from the tuple into the variables n1, n2, and n3
n1, n2, n3 = tuplex
# Calculate and print the sum of n1, n2, and n3
print(n1 + n2 + n3)

# Attempt to unpack the tuple into more variables (n1, n2, n3, and n4)
# This will raise a "ValueError" since there are not enough values in the tuple to unpack into all the variables
n1, n2, n3, n4 = tuplex

Sample Output:

(4, 8, 3)                                                                                                     
15                                                                                                            
Traceback (most recent call last):                                                                            
  File "32fd05c0-3096-11e7-a6a0-0b37d4d0b2c6.py", line 8, in <module>                                         
    n1, n2, n3, n4 = tuplex                                                                                   
ValueError: not enough values to unpack (expected 4, got 3) 

Flowchart:

Flowchart: Unpack a tuple in several variables

Python Code Editor:

Previous: Write a Python program to create a tuple with numbers and print one item.
Next: Write a Python program to add an item in a tuple.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.