Multiple Assignments Python
>>> x=y=z=1 >>> x 1 >>> y 1 >>> z 1
In the above example, an integer object (with the value 1) is created, and x, y, and z are all assigned the same reference to that object. This is the process of assigning a single object to multiple variables. It is also possible in Python to assign multiple objects to multiple variables.
How to Do a “Multuple” Assignment
Another way of assigning multiple variables is using what we shall call the “multuple” assignment. This is not an official Python term, but we use “multuple” here because when assigning variables this way, the objects on both sides of the equals sign are tuples, a Python standard type.
>>> x,y,z=1,2,'a string' >>> x 1 >>> y 2 >>> z 'a string'
In the above example, two integer objects (with values 1 and 2) and one string object are assigned to x, y, and z respectively. Parentheses are normally used to denote tuples, and although they are optional, we recommend them anywhere they make the code easier to read:
>>> (x,y,z) = (1,2,' a for apple')
If you have ever needed to swap values in other languages like C, you will be reminded that a temporary variable, i.e., tmp, is required to hold one value which the other is being exchanged:
/* swapping variables in C */ tmp = x; x = y; y = tmp;
In the above C code fragment, the values of the variables x and y are being exchanged. The tmp variable is needed to hold the value of one of the variables while the other is being copied into it. After that step, the original value kept in the temporary variable can be assigned to the second variable.
One interesting side effect of Python’s “multuple” assignment is that we no longer need a temporary variable to swap the values of two variables.
>>> (x,y) = (1,2) >>> x 1 >>> y 2 >>> (x,y) = (y,x) >>> x 2 >>> y 1