Inline Assignment in Python
In Python, you can assign multiple values to multiple variables simultaneously using a single assignment statement.
var1, var2 = value1, value2
or
var1, var2 = (value1, value2)
A Practical Example
Example 1
I have a tuple that contains the x, y, z coordinates of a 3D Cartesian diagram.
To assign each value of the tuple to a different variable, I can write:
- data = (1, 2, 3)
- x, y, z = data
- print(x, y, z)
This script assigns each value from the tuple to the variable in sequence.
The output of the program is:
1
2
3
Example 2
In this script, I use inline assignment to assign three values to three variables.
- x, y, z = 1, 2, 3
- print(x, y, z)
This script assigns the values to the variables following the order of assignment.
The output of the program is:
1
2
3
And so on.