The difference is that one modifies the data-structure itself (in-place operation) b += 1 while the other just reassigns the variable a = a + 1.
Just for completeness:
x += y is not always doing an in-place operation, there are (at least) three exceptions:
-
If
xdoesn’t implement an__iadd__method then thex += ystatement is just a shorthand forx = x + y. This would be the case ifxwas something like anint. -
If
__iadd__returnsNotImplemented, Python falls back tox = x + y. -
The
__iadd__method could theoretically be implemented to not work in place. It’d be really weird to do that, though.
As it happens your bs are numpy.ndarrays which implements __iadd__ and return itself so your second loop modifies the original array in-place.
You can read more on this in the Python documentation of “Emulating Numeric Types”.
These [
__i*__] methods are called to implement the augmented arithmetic assignments (+=,-=,*=,@=,/=,//=,%=,**=,<<=,>>=,&=,^=,|=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self). If a specific method is not defined, the augmented assignment falls back to the normal methods. For instance, if x is an instance of a class with an__iadd__()method,x += yis equivalent tox = x.__iadd__(y). Otherwise,x.__add__(y)andy.__radd__(x)are considered, as with the evaluation ofx + y. In certain situations, augmented assignment can result in unexpected errors (see Why doesa_tuple[i] += ["item"]raise an exception when the addition works?), but this behavior is in fact part of the data model.