Python += 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:

As you can notice, a2 = a2 + [3] expression only modifies the list on which it is operating, but b2 += [3] changes the values of both b1 and b2.

Why list =list + list behaves differently from list += list?

It is because of the difference in the implementation of the __iadd__ and __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.

The inbuilt __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.

Since __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 + b in Python.

Conclusion

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.

Leave a Reply