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)?

Why Does Multiple Assignment in Python (x, y = y, x y) Differ from Separate Assignments (x = y; y = x y)?

Susan Sarandon
Susan SarandonOriginal
2024-12-15 17:52:10918browse

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:

  1. y is evaluated and stored as ham.
  2. x y is evaluated and stored as spam.
  3. x is set to ham.
  4. y is set to spam.

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:

  1. y is set to x.
  2. x y is evaluated as y y and set to y.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn