Mutable vs immutable

Applies to: python, general

A mutable object can be changed in place (a list, a dict); an immutable one cannot (a tuple, a string, a number), so "changing" it makes a new object. This matters for sharing: two names can see the same mutable object and one's change affects the other.

a = [1, 2]; b = a; b.append(3)   # a is now [1,2,3] (shared, mutable)
s = "hi"; s2 = s + "!"           # strings are immutable; s2 is new

See also: tuple, reference