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
or dict
, but int
and str
are immutable).
In a = a + b
, a
is evaluated twice.
Python: Simple Statements
- 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], [])
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…