Contrary to some existing answers here, the real reason actually the opposite. +=
is meant to be an in-place operator that modifies self in Python. But there's some catch to it.
For immutable types such as tuples and strings, my_tuple += (1, )
is equivalent to my_tuple = my_tuple + (1, )
which creates a new object then assigns it to my_tuple
:
>>> my_tuple = (1,2,3)
>>> t = my_tuple
>>> t += (2,)
>>> t
(1, 2, 3, 2)
>>> my_tuple
(1, 2, 3)
This is because immutable types such as tuples and strings do not implement __iadd__
(you can check by dir(tuple)
for example). And in this case it falls back to use __add__
instead. This will create a new object and assign it to the original variable.
For some mutable types such as lists and dictionaries, however, __iadd__
is implemented, and +=
will be calling it instead:
>>> inspect.getdoc(list.__iadd__)
'x.__iadd__(y) <==> x+=y'
>>> a = [1,2,3]
>>> b = a
>>> b += [4]
>>> b
[1, 2, 3, 4]
>>> a
[1, 2, 3, 4]
So for mutable types, this in-place operation is performed (by modifying self) and the original object will be updated.