Home > Backend Development > Python Tutorial > How Does Python's Multiple Assignment Affect Variable Evaluation Order?

How Does Python's Multiple Assignment Affect Variable Evaluation Order?

Susan Sarandon
Release: 2024-12-16 14:43:10
Original
616 people have browsed it

How Does Python's Multiple Assignment Affect Variable Evaluation Order?

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

After this assignment, the values of x and y are:

>>> x
2
>>> y
3
Copy after login

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template