Multiple Assignment and Evaluation Order in Python
In Python, multiple assignments are a common practice, where multiple variables are assigned values simultaneously. However, the order of evaluation in such assignments can have unexpected consequences.
The Problem
Consider the following code:
>>> x = 1 >>> y = 2 >>> x, y = y, x + y # Multiple assignment
After this assignment, the values of x and y are:
>>> x 2 >>> y 3
This differs from what one might expect if the assignments were done separately:
>>> x = 1 >>> y = 2 >>> x = y # Assign x to the current value of y >>> y = x + y # Assign y to the sum of x and y >>> x 2 >>> y 4
The Explanation
The difference arises due to the order of evaluation in assignment statements. In Python, the right-hand side of an assignment is evaluated first, before the actual assignment to the variables takes place.
In the first example, when we assign x, y = y, x y, the right-hand side is evaluated as follows:
ham = y # Where ham = 2 spam = x + y # Where spam = 1 + 2 = 3
Then, x is assigned the value of ham (2), and y is assigned the value of spam (3). This is why we get the result x = 2 and y = 3.
In contrast, in the second example, x is first assigned the value of y, which is 2. Then, y is assigned the sum of x (2) and y (2), resulting in 4.
The above is the detailed content of How Does Python's Multiple Assignment Affect Variable Evaluation Order?. For more information, please follow other related articles on the PHP Chinese website!