This is an answer not to the original question (which I think has been adequately answered), but to the numerous questions that have been asked in the comments about the semantics of augmented assignment (+=
and similar operations).
In a nutshell: Augmented assignment works differently for mutable types than for immutable ones.
str
, tuple
, and the numeric types, among others, are immutable. The contents of a tuple cannot be changed once it has been created, so you get this behavior:
>>> a = (1, 2)
>>> b = a
>>> a += (3, 4)
>>> a
(1, 2, 3, 4)
>>> b
(1, 2)
str
has the same semantics. Basically, a += b
is equivalent to a = a + b
if a
is immutable.
Most other types, including list
, are mutable. A list's contents can be changed in place, and augmented assignment does exactly that. Hence:
>>> a = [1, 2]
>>> b = a
>>> a += [3, 4]
>>> a
[1, 2, 3, 4]
>>> b
[1, 2, 3, 4]
Whereas if the third line were replaced with a = a + [3, 4]
, a new list would be created and b
would be [1, 2]
.
For a user-defined class, the semantics depend on how it was implemented, but this is how it's supposed to be done per PEP 203.