Home  >  Article  >  Backend Development  >  Why does `list.__iadd__` modify both original and assigned lists, while `list.__add__` only modifies the assigned list?

Why does `list.__iadd__` modify both original and assigned lists, while `list.__add__` only modifies the assigned list?

Susan Sarandon
Susan SarandonOriginal
2024-10-30 17:05:25539browse

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:

    • Mutates the original list (x) in-place
    • Extends it with the elements from the second list ([4])

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:

  • x [4] creates a new list by concatenating x with [4]
  • The x variable is then reassigned to this new list
  • y remains unchanged since it is a different object

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!

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