A chained assignment in Python, such as:
x = y = somefunction()
is equivalent to the following two statements executed sequentially:
temp = somefunction() x = temp y = temp
This means that the expression on the right-hand side of the assignment operator is evaluated first, and the resulting value is then assigned to all of the variables on the left-hand side, from left to right.
For example, the following code will print the number 10 twice:
def somefunction(): return 10 x = y = somefunction() print(x) print(y)
It's important to note that chained assignments can be problematic when dealing with mutable objects, such as lists. For example, the following code assigns the same empty list to both x and y:
x = y = [] x.append(1) print(x) print(y)
This will print [1, 1] because both x and y refer to the same list. If you intended to create two separate lists, you should instead write:
x = [] y = [] x.append(1) print(x) print(y)
This will print [1] and [] because x and y refer to different lists.
The above is the detailed content of How do chained assignments work in Python, and what are the potential pitfalls when dealing with mutable objects?. For more information, please follow other related articles on the PHP Chinese website!