How do Chained Assignments Work in Python?

Patricia Arquette
Release: 2024-11-02 09:38:02
Original
875 people have browsed it

 How do Chained Assignments Work in Python?

Chained Assignments in Python

In Python, chained assignments using the syntax x = y = somefunction() are equivalent to y = somefunction(); x = y. This means that the value returned by the function is first assigned to the leftmost target, and then the same value is assigned to the subsequent targets.

However, a common misconception is that chained assignments such as x = y = somefunction() are equivalent to x = somefunction(); y = somefunction(). This is not the case.

Left-to-Right Evaluation

The key to understanding chained assignments is to remember that Python evaluates expressions and statements from left to right. This means that in the expression x = y = somefunction(), the following steps occur:

  1. somefunction() is evaluated, and the result is stored in a temporary variable (let's call it temp).
  2. x is assigned the value of temp.
  3. y is also assigned the value of temp.

As a result, x and y end up referring to the same object.

Implications

This left-to-right evaluation can have important implications. For example, if somefunction() returns a mutable object such as a list, assigning to one of the targets will affect all other targets that refer to the same object.

Example:

Consider the following code:

<code class="python">x = y = []
x.append(1)
print(x, y)</code>
Copy after login

The output of the above code will be [1, 1] because x and y refer to the same list object. Any changes made to one of the targets will be reflected in the other targets.

Conclusion

Chained assignments in Python are evaluated from left to right, resulting in the same object being assigned to all targets. This can have important implications when dealing with mutable objects, as changes to one target can affect all references to the same object.

The above is the detailed content of How do Chained Assignments Work in Python?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!