Unpacking Tuples in Python
So far, we are familiar with many different things related to the tuple. So, now we are going to have a look at tuple unpacking, which simply means splitting the tuple elements, into individual variables. Let’s have a look at a simple program, which demonstrates how we can do this tuple unpacking.
As you can see in the above program, we have a simple tuple. Notice that we do not have the parentheses here, but the elements are separated by commas, which demonstrates that we can create tuples in such a way as well. After that, we are doing the unpacking, which simply means splitting the tuple elements into individual variables. Now, since there are 4 elements in the tuple, we have 4 variables here. Then accordingly, we are printing the variables. This is the output of the above program.
GyaniPandit
True
Python
2.9
As you can see, we got the corresponding output from the program. Now, in the previous example, we had four elements to unpack, and we had four variables, so everything was fine. But now, Let’s say that there are more values in the tuple, and we have a lesser number of variables, then we are going to get into an error. Let’s have a look at that too.
As you can see, in the above program, we have 4 elements in the tuple, and then we are having only three variables. In such a situation, we get an error, which says – ValueError: too many values to unpack (expected 3).
You can get a similar message, but it depends on how many variables you have given. But the thing is that it says too many values to unpack.
Now, in order to overcome this, we can do one thing. We can use an asterisk before some variable, and then the values would be assigned as a list, to the variable. Let’s have a look at the below program, to understand the same thing.
As you can see in the above program, we have a tuple, which has 9 values, and then we have 4 variables. But the thing is that before the fourth variable, we have made use of the asterisk, so the values here would be added as a list, and in the output, you would find the other values in the list. Let’s have a look at the output of the above program.
1
2
3
[4, 5, 6, 7, 8, 9]
As you can see, we have got the output. Also, it is not a compulsion to use the asterisk at the ending variable only. We can use it for any variable. Let’s have a look at the program below.
As you can see, in the below program, we have used the asterisk before the num2 variable, so now, the values in the num2 would be assigned as a list. But the thing is that after that, we have two more variables there. So, only two values would be left for those variables in the end, and the other values before that would go into the list. Let’s have a look at the output now –
1
[2, 3, 4, 5, 6, 7]
8
9
As you can see, in the output, the first variable got a value, and then the second variable got a list, as specified, and then we have the other two values. So, performing this is very easy, and can be useful at times.