Augmented assignment operators such as +=
and *=
behave differently depending on whether the Python object is mutable or immutable. Let’s take +=
as an example: Python first checks if the first object implements __iadd__
special method. If not, Python falls back on __add__
. Since immutable objects don’t implement any inplace operations, statement like x += y
is the same as x = x + y
.
For mutable objects such as lists:
= [1, 2]
l = id(l)
old_id += [3] # the same as l.extend([3])
l print(l) #=> [1, 2, 3]
== id(l) #=> True old_id
For mutable objects such as tuples:
= [1, 2]
t = id(t)
old_id += (3,) # the same as t = t + (3,)
t print(t) #=> (1, 2, 3)
== id(t) #=> False old_id