Python a + = b and a = a + b are different

Some sites say that the operator ʻa + = b` is the same as ʻa = a + b`, but it is not exactly the same for mutable objects. Be careful if you have variables that point to the same object. (Especially for those who use NumPy!)

Overview

In a nutshell, there are the following differences. For mutable objects,

--In ʻa + = b`, the object pointed to by ʻa` does not change before and after the assignment. --When ʻa = a + b`, the object pointed to by ʻa` changes before and after the assignment.

However, for immutable objects, it changes in both cases (@shiracamus's comment has an example).

Experiment

Let's experiment with adding `[3]` to `[1, 2]` to create `[1, 2, 3]`. `y` refers to the object of` x` before assignment. You can get the ID of an object with the built-in function ʻid (x) `.

`a += b`

``````>>> x = y = [1, 2]  #y is the same object as x before assignment
>>>
>>> id(x)
4397797440
>>> id(y)
4397797440
>>>
>>> x += [3]
>>>
>>> ｘ
[1, 2, 3]
>>> y  #Also added to y
[1, 2, 3]
>>>
>>> id(x)  #Same object as before assignment
4397797440
>>> id(y)
4397797440
``````

`a = a + b`

``````>>> x = y = [1, 2]  #y is the same object as x before assignment
>>>
>>> id(x)
4397797440
>>> id(y)
4397797440
>>>
>>> x = x + [3]
>>>
>>> ｘ
[1, 2, 3]
>>> y  #Not added to y
[1, 2]
>>>
>>> id(x)  #Point to an object different from the one before the assignment
4395937472
>>> id(y)
4397797440
``````