Home  >  Article  >  Backend Development  >  How do chained assignments work in Python, and what are the potential pitfalls when dealing with mutable objects?

How do chained assignments work in Python, and what are the potential pitfalls when dealing with mutable objects?

Linda Hamilton
Linda HamiltonOriginal
2024-10-27 10:10:03916browse

How do chained assignments work in Python, and what are the potential pitfalls when dealing with mutable objects?

How do chained assignments work?

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!

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