+= operator is often used for concatenating list in Python. Python
+= list expression is similar to the
list + list expression but they operate differently.
Consider the following example in Python:
a1 = a2 = [1, 2] a2 = a2 +  print(a1) # output [1, 2] print(a2) # output [1, 2, 3] b1 = b2 = [1, 2] b2 +=  print(b1) # output [1, 2, 3] print(b2) # output [1, 2, 3]
As you can notice,
a2 = a2 +  expression only modifies the list on which it is operating, but
b2 +=  changes the values of both
Why list =list + list behaves differently from list += list?
It is because of the difference in the implementation of the
__add__ methods in Python.
+= tries to call the
__iadd__ method associated with the operating object, if it is not available it uses
_add_ method instead.
__iadd__ method implements in-place addition, that is it mutates the object that it acts on. whereas the
__add__ method returns a new object after the addition operation.
__iadd__ mutates the object that it acts on, it is only available for mutable types like a list.
For immutable types like string, tuple, integer, etc (where the
__iadd__ is not available) the
a += b expression becomes equivalent to
a = a + b and as a result the plain
__add__ method is used which returns a new object.
It is __add__ method, which is called behind the scenes when we use
a = a + bin Python.
The use of
+= on mutable object mutates the object i.e. the reference remains the same. For immutable object a new reference is returned as a result.
That’s why using
+= on a list changes the values of all list referencing the same object.