Table of Contents
ToggleTuples in Python are immutable, ordered collections of elements. This guide explains how to unpack tuple items into individual variables using different techniques.
The term “unpacking” refers to the process of parsing tuple items into individual variables. In Python, the parentheses are optional for a tuple declaration.
t1 = (x, y)
t1 = x, y
print(type(t1)) # Output:
To store tuple items in individual variables, use multiple variables on the left of the assignment operator.
tup1 = (10, 20, 30)
x, y, z = tup1
print("x:", x, "y:", y, "z:", z) # Output: x: 10 y: 20 z: 30
If the number of variables does not match the number of items in the tuple, Python raises a ValueError.
tup1 = (10, 20, 30)
x, y = tup1 # ValueError: too many values to unpack (expected 2)
x, y, p, q = tup1 # ValueError: not enough values to unpack (expected 4, got 3)
The “*” symbol is used for unpacking when the number of variables does not match the tuple size.
tup1 = (10, 20, 30)
x, *y = tup1
print("x:", x, "y:", y) # Output: x: 10 y: [20, 30]
tup1 = (10, 20, 30, 40, 50, 60)
x, *y, z = tup1
print("x:", x, "y:", y, "z:", z) # Output: x: 10 y: [20, 30, 40, 50] z: 60
tup1 = (10, 20, 30, 40, 50, 60)
*x, y, z = tup1
print("x:", x, "y:", y, "z:", z) # Output: x: [10, 20, 30, 40] y: 50 z: 60
