Multiple Assignment Mystery in Python
In Python, assignments can be evaluated in ways that may not be immediately obvious. One such case is multiple assignment, where two or more variables are assigned values simultaneously.
Consider the following:
>>> x = 1 >>> y = 2
Now, let's attempt to assign both values at once:
>>> x, y = y, x + y >>> x 2 >>> y 3
Unexpectedly, this produces different results compared to assigning the values separately:
>>> x = 1 >>> y = 2 >>> x = y >>> y = x + y >>> x 2 >>> y 4
Explanation
The key to understanding this behavior lies in the order of evaluation in an assignment statement. In Python, the right-hand side of an assignment is always evaluated completely before the actual setting of variables.
In the first case, "x, y = y, x y", the right-hand side evaluates as follows:
The variables are then set to these values: x is assigned ham, and y is assigned spam.
In contrast, in the second case, "x = y; y = x y", the assignments happen sequentially: x is set to y, and then y is set to x y, which is equivalent to y y.
Therefore, the multiple assignment in the first case behaves differently because the values are evaluated and set concurrently. If you want to perform separate assignments, you should use the latter, sequential approach.
The above is the detailed content of How Does Python's Multiple Assignment Differ from Sequential Assignment?. For more information, please follow other related articles on the PHP Chinese website!