Tuple Unpacking
Tuple is a collections of data (of different data types) and are created by specifying the data (or variables) inside round brackets. We can also call this as Tuple packing. See more about working with tuples.
So, what is tuple unpacking? As the name suggests unpacking the data from a tuple into variables is called tuple unpacking.
Let's have a quick look at the creation of a tuple (packing) and unpacking of a tuple.
# Numeric data
num_one = 1
# Character data
char_one = "ONE"
# Create Tuple (Packing)
new_tuple = (num_one, char_one)
# Unpacking Tuple
unpack_num, unpack_char = new_tuple
print(unpack_num)
print(unpack_char)- Line - 2: Creating variable num_one to store a number (1).
- Line - 4: Creating variable char_one to store a string (ONE).
- Line - 8: Creating a tuple by mentioning the variables created inside round brackets (num_one, char_one). This can also be done by directly providing the data inside round brackets (1, "ONE").
- Line - 11: Unpacking the tuple, unpacking the data in a tuple into different variables. First element in the tuple would be assigned to the first variable and second element in the tuple would be assigned to the second variable.
- Lines - 13 & 14: Printing the data from the unpacked variables.
We have not used round brackets to do the tuple unpacking. But, this should work in the same way even if we specify the variables inside round brackets for unpacking the data from a tuple.
# Unpacking Tuple
(unpack_num, unpack_char) = new_tupleWhat to do if there are more number of elements in the tuple than the variables?
Tuple unpacking would fail with "ValueError: too many values to unpack".
# Create Tuple (Packing)
new_tuple = (num_one, char_one, True)
# Unpacking Tuple
(unpack_num, unpack_char) = new_tupleTraceback (most recent call last):
File "/Users/Admin/PycharmProjects/pythonProject/main.py", line 11, in <module>
(unpack_num, unpack_char) = new_tuple
ValueError: too many values to unpack (expected 2)If this is intended and group of tuple elements should be assigned to a single variable (as list), this can be done by using asterisk (*) before the variable.
Let's take a look at different example to understand this better.
# Create Tuple with Color and Fruit names
fruit_tuple = ("Red", "Apple", "Strawberry")
# Use asterisk before the list variable
color, *fruits = fruit_tuple
print(color) # Red
print(fruits) # ['Apple', 'Strawberry']- Tuple has three elements.
- First element is the color.
- Second and Third elements are the fruits in the specific color.
If we use the variable names color and fruits as it is, ValueError would be thrown. So, we are using asterisk (*) before 'fruits' which needs to store the fruits as a list.
Result here would be,
- Mapping of first variable to the first element (no asterisk for color, so would consider as one to one mapping).
- Mapping of second variable (list) to the remaining elements in the tuple.
- An empty list would be created if there is no corresponding data present in the tuple.
color, *fruits = ("Red",)
print(color) # 'Red'
print(fruits) # []- A list would be created with just one element if there is only one corresponding entry in the tuple. Unlike the the variable with the type of data (if asterisk is not used).
color, *fruits = ("Red", "Apple")
print(color) # 'Red'
print(fruits) # ['Apple']- A list would be created with multiple elements if there are multiple entries in the tuple.
color, *fruits = ("Red", "Apple", "Strawberry")
print(color) # 'Red'
print(fruits) # ['Apple', 'Strawberry]Let's take if we use asterisk before the color in the above example.
*color, fruits = ("Red", "Apple", "Strawberry")
print(color) # ['Red', 'Apple']
print(fruits) # 'Strawberry'We can only have one starred expression in an assignment.
Let's take another example with three variables.
color, *fruits, taste = ("Red", "Apple", "Strawberry", "Cherry", "Sweet")
print(color) # 'Red'
print(fruits) # ['Apple', 'Strawberry', 'Cherry']
print(taste) # 'Sweet'In this example,
- We are using three variables and given asterisk for the middle variable.
- First and Last elements in the tuple are assigned to the first and last variables.
- All other elements in the middle (from Tuple) are assigned as a list to the starred variable.
Tuple unpacking would be helpful in many scenarios. We will have a look at how we can use tuple unpacking with dictionaries to unpack key and value from dictionary.
Dictionary method items would return each key and value combination as a tuple.
# Create a dictionary with color and fruit names
fruit_dict = {"Red": "Apple", "Orange": "Orange", "Yellow": "Banana"}
for item in fruit_dict.items():
print(item)
# Tuple with Key and Value would be printed.
# ('Red', 'Apple')
# ('Orange', 'Orange')
# ('Yellow', 'Banana')Let's use tuple unpacking to unpack key and values.
# Create a dictionary with color and fruit names
fruit_dict = {"Red": "Apple", "Orange": "Orange", "Yellow": "Banana"}
for key, value in fruit_dict.items():
print(key)
# Key would be printed
print(value)
# Value would be printedHope the above info was useful in understanding Tuple unpacking in Python.