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

Susan Sarandon
Release: 2024-10-30 17:05:25
Original
601 people have browsed it

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

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

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!

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