Home > Article > Backend Development > Why does `list.__iadd__` modify both original and assigned lists, while `list.__add__` only modifies the assigned list?
Behavior Discrepancy between list.__iadd__ and list.__add__
Consider the following snippet:
<code class="python">x = y = [1, 2, 3, 4] x += [4] print(x) # Outputs: [1, 2, 3, 4, 4] print(y) # Outputs: [1, 2, 3, 4, 4]</code>
In contrast, observe this:
<code class="python">x = y = [1, 2, 3, 4] x = x + [4] print(x) # Outputs: [1, 2, 3, 4, 4] print(y) # Outputs: [1, 2, 3, 4]</code>
Why do these two code snippets behave differently?
Explanation
The key difference lies in the use of the " " operator. In the first snippet:
x = [4] uses the __iadd__ method of the list class, which:
This results in both x and y being modified to include the value 4.
In the second snippet, however, x = x [4] uses the __add__ method:
Therefore, x has the value [1, 2, 3, 4, 4] while y still holds the original value [1, 2, 3, 4].
The above is the detailed content of Why does `list.__iadd__` modify both original and assigned lists, while `list.__add__` only modifies the assigned list?. For more information, please follow other related articles on the PHP Chinese website!