Mutability and Inplace Operations

Python
Author

Imad Dabbura

Published

September 12, 2022

For immutable objects, inplace operation such as “+=” creates a new object and assign the variable to the newly created object.

s = "test"
old_id = id(s)
s += " another test"
old_id == id(s) #=> False

But for mutable objects, it doesn’t create a new object. It extends/updates the existing object.

l = [1]
old_id = id(l)
l += [2]
old_id == id(l) #=> True