Home >Backend Development >Python Tutorial >Why Does Multiple Assignment in Python (x, y = y, x y) Differ from Separate Assignments (x = y; y = x y)?
Multiple Assignment and Evaluation Order in Python
In Python, when utilizing multiple assignment, such as x, y = y, x y, it's imperative to understand the underlying order of evaluation.
Question:
When assigning multiple values at once, why does x, y = y, x y result in different values than assigning them separately, i.e. x = y; y = x y?
Answer:
In Python, the right-hand side of an assignment statement is evaluated fully before any variable setting occurs. This implies that in x, y = y, x y, the following steps take place:
Effectively, it's equivalent to:
ham = y spam = x + y x = ham y = spam
On the other hand, in x = y; y = x y, the steps are:
This results in x being set to the original value of y, and y being set to the sum of the original values of x and y.
The above is the detailed content of Why Does Multiple Assignment in Python (x, y = y, x y) Differ from Separate Assignments (x = y; y = x y)?. For more information, please follow other related articles on the PHP Chinese website!