a += b
is essentially the same as a = a + b
, except that:
-
+
always returns a newly allocated object, but+=
should (but doesn’t have to) modify the object in-place if it’s mutable (e.g.list
ordict
, butint
andstr
are immutable). -
In
a = a + b
,a
is evaluated twice. -
- A simple statement is comprised within a single logical line.
If this is the first time you encounter the +=
operator, you may wonder why it matters that it may modify the object in-place instead of building a new one. Here is an example:
# two variables referring to the same list
>>> list1 = []
>>> list2 = list1
# += modifies the object pointed to by list1 and list2
>>> list1 += [0]
>>> list1, list2
([0], [0])
# + creates a new, independent object
>>> list1 = []
>>> list2 = list1
>>> list1 = list1 + [0]
>>> list1, list2
([0], [])