In the first example, you are reassigning the variable a
, while in the second one you are modifying the data in-place, using the +=
operator.
See the section about 7.2.1. Augmented assignment statements :
An augmented assignment expression like
x += 1
can be rewritten asx = x + 1
to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.
+=
operator calls __iadd__
. This function makes the change in-place, and only after its execution, the result is set back to the object you are "applying" the +=
on.
__add__
on the other hand takes the parameters and returns their sum (without modifying them).