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:
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>
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!