Let us say, we have a Tuple that contains three names, 'Mohan', 'Kriti' and 'Salim'. And when we assign it to a variable, it is called as 'Packing'.
x = ("Mohan", "Kriti", "Salim") print(x)
Now, Python provides a way to assign each values to a Tuple to individual variables.
Let us see with the below example.
So, in the above code we have created a 'Tuple' and initialised to the variable 'x'.
Below is how the values are positioned in the Tuple,
x = ("Mohan", "Kriti", "Salim") (i, j, k) = x print(i) print(j) print(k)
So, we have created a 'Tuple' with three elements, 'Mohan', 'Kriti' and 'Salim'. And assigned them to a variable 'x'.
In the next line, we have 'UnPacked' the 'Tuple' elements to variables, 'i', 'j' and 'k'.
And the first element of the 'Tuple' (i.e. 'Mohan') is assigned to the variable 'i'.
The second element of the 'Tuple' (i.e. 'Kriti') is assigned to the variable 'j'.
Finally, the third element of the 'Tuple' (i.e. 'Salim') is assigned to the variable 'k'.
And the print statement,
Prints the values,
But what if we the number of variables are not equal to the number of elements in the 'Tuple'?
In that case you can use an Asterisk '*' any one variable.
Let us see with the below example.
x = ("Mohan", "Kriti", "Salim") (i, *j) = x print(i) print(j)
And as usual, we have created a 'Tuple' with three elements, 'Mohan', 'Kriti' and 'Salim'.And assigned them to a variable 'x'.
In the next line, we have 'UnPacked' the 'Tuple' elements to variables, 'i' and 'j'.
But the number of elements in the 'Tuple' are three. Which is a mismatch.
And what we do is put an asterisk '*' at in front of the second variable 'j'.
And what happens is,
The first element of the 'Tuple' (i.e. 'Mohan') is assigned to the variable 'i'.
And the second an third element of the 'Tuple' (i.e. 'Kriti' and 'Salim') is assigned to the variable 'j', forming a List.
And the print statement,
Prints the String 'Mohan',
And since the variable 'j' is a List. So, the print statement,
Prints the List,
Let us see another example with asterisk '*'.
x = ("Mohan", "Kriti", "Salim") (*i, j) = x print(i) print(j)
And in the above program, the List is formed with 'Mohan' and 'Kriti' and is assigned to the variable 'i'.