Main Content

Beware - a=a+b and a+=b are different - Python

Archive - Originally posted on "The Horse's Mouth" - 2011-02-23 07:32:31 - Graham Ellis

It's commonly stated the the += operator is simply a more efficient and shorter to code alternative to using a + operator and saving back to the same variable ... in other words that
  original += extra
and
  original = original + extra
do the same thing.

But - in Python at least - that's not quite the case. If we had given the original variable another name prior to the operation above:
  aka = original
and we modify the alternative name after the operation:
  aka[1] = 5
we will get different results when we print out original again.

Using "+" original is unchanged by the reassignment on an element:
  [2, 4, 6, 8, 10, 12, 14, 16]
But using +=, aka remains an alias to the variable, so it is changed:
  [2, 5, 6, 8, 10, 12, 14, 16]

There are complete samples using += [here] and using reassignment [here] in our source library.

Note - if you are defining your own class, you can set up the + and += operator to perform completely different actions if you like, by defining the __add__ and __iadd__ methods with different code.