0

I need help understanding the following code:

**Example 1**
v1 = v2 = ['h', 'e', 'l', 'l', 'o']
v1 += ['w', 'o', 'r', 'l', 'd']
print(v1==v2)  #True, v1 and v2 reference the same object

**Example 2**
v1 = v2 = ['h', 'e', 'l', 'l', 'o']
v1 = v1 + ['w', 'o', 'r', 'l', 'd']
print(v1==v2)  #False, v1 and v2 no longer reference the same object

Question:

From my understanding, a += 1 is the same as a = a + 1.

Why then, is v1 += ['w', 'o', 'r', 'l', 'd'] different from v1 = v1 + ['w', 'o', 'r', 'l', 'd']?

source: mutable objects changed in-place means what?

  • From [PEP 203](https://www.python.org/dev/peps/pep-0203/) which introduced augmented assignment: "The idea behind augmented assignment in Python is that it isn't just an easier way to write the common practice of storing the result of a binary operation in its left-hand operand, but also a way for the left-hand operand in question to know that it should operate on itself, rather than creating a modified copy of itself." – John Coleman Mar 09 '21 at 16:11
  • 1
    `+=` calls `__iadd__` which mutates the list **in-place**, in latter example `v1 + [...]` a new object is created and you named it `v1` – Ch3steR Mar 09 '21 at 16:11

0 Answers0