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

Linda Hamilton
Release: 2024-10-27 10:10:03
Original
1016 people have browsed it

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

is equivalent to the following two statements executed sequentially:

temp = somefunction()
x = temp
y = temp
Copy after login

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

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

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

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!

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