Home > Backend Development > Python Tutorial > How Does Python's Multiple Assignment Differ from Sequential Assignment?

How Does Python's Multiple Assignment Differ from Sequential Assignment?

DDD
Release: 2024-12-05 02:26:09
Original
320 people have browsed it

How Does Python's Multiple Assignment Differ from Sequential Assignment?

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
Copy after login

Now, let's attempt to assign both values at once:

>>> x, y = y, x + y
>>> x
2
>>> y
3
Copy after login

Unexpectedly, this produces different results compared to assigning the values separately:

>>> x = 1
>>> y = 2
>>> x = y
>>> y = x + y
>>> x
2
>>> y
4
Copy after login

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:

  • y is evaluated to ham.
  • x y is evaluated to spam.

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template