In Python, packing is the process of adding items to a tuple.
But, in contrast, unpacking involves extracting items from a tuple back to variables.
colors_tuple = ("Red", "Blue", "Green") # packing tuple.
(apple, blueberries, grapes) = colors_tuple # unpacking tuple.
print(apple)
print(blueberries)
print(grapes)
'Red'
'Blue'
'Green'
In the above example, the color tuple unpacks, and fruit names assign according to their color names, which are in the tuple. Whenever we print the fruit name variables, we get the color names of the fruits.
*
)When the number of variables is less than the number of items in the tuple, use an asterisk (*
) with the variable name, and in the output, you will get a list of values for the variable.
colors_tuple = ("Red", "Blue", "Green", "Black", "Purple")
(apple, blueberries, *grapes) = colors_tuple
print(apple)
print(blueberries)
print(grapes)
'Red'
'Blue'
['Green', 'Black', 'Purple']
In the above example, we declared three variables and the third variable with an asterisk, so as in the output, you can see the first two variables has single item values and a list of items for the third variable.
If you add an asterisk (*
) to another variable name than the last variable, then Python will assign values to the asterisk variable until the number of values left matches the number of variables left.
colors_tuple = ("Red", "Blue", "Green", "Black", "Purple")
(apple, *blueberries, grapes) = colors_tuple
print(apple)
print(blueberries)
print(grapes)
'Red'
['Blue', 'Green', 'Black']
'Purple'
In the above example, we declared three variables and the second variable with an asterisk, so as in the output, you can see the first and third variables has single item values and a list of items for the second variable.
A syntax error will occur if you add an asterisk (*
) to more than one variable name.
colors_tuple = ("Red", "Blue", "Green", "Black", "Purple")
(apple, *blueberries, *grapes) = colors_tuple
print(apple)
print(blueberries)
print(grapes)
SyntaxError: multiple starred expressions in assignment
When we unpack the tuple, we added an asterisk to the second and third variable names, resulting in a syntax error (SyntaxError: multiple starred expressions in assignment
).