To create a tuple, firstly we assign values to this tuple. In other words, we do Python Tuple Packing. In this lesson, we will do the reverse of this, Python Tuple Unpacking. With Tuple Unpacking, we will extract the values back into variables.
So, let’s firstly check do Python Tuple Packing. Here, we will add values to the tuple, we will create tuple. Out tuple example will include some of the characters of the lord of the rings.
The output of this Python Tuple Packing code will be like below:
Now, let’s do Python Tuple Unpacking. We will do this with the below example.
The output of this code will be like below:
You can also wtach the video version of this lesson!
Here, the number of the variables and the number of the memebrs in tuple must be same. If these numbers are not same, then we can use asterisk (*). If we use this sign, then the remaining values are assigned same. Let’s do an example for this.
In the output of this Python Tuple Unpacking example code will be like below:
As you can see here, because of the fact that we use asterisk (*) with “elf”, the tuple members after it all defined as elf.
Like Python Tuple Packing, you can use Tuple Unpacking for different purposes. You can extract the values into variables and use them in your code.