Python - The difference of mutable and immutable objects

In Python, all are objects. An integer, float, string, list, tuple are objects and a class and function are also objects. Python objects are immutable or mutable.

Immutable object

  • bool
  • int
  • float
  • string
  • tuple
  • frozenset

Mutable object

  • list
  • dictionary
  • set

A mutable object can be (unexpectedly) changed but an immutable object doesn't change. 1 is 1, (5, 7) is (5, 7).

Immutable object

A tuple can't change because it is immutable. Integers are immutable so variables assigned the same value have the same ids.

a = 1
print(id(a))  # 4300839120
print(id(1))  # 4300839120

a = 3
print(id(a))  # 4300839184
print(id(3))  # 4300839184

Mutable object

A list can be modified because it is mutable. So it has the append() or pop() methods.

a = [1, 2]
print(id(a))  # 4491350400

print(id(a))  # 4491350400

The id doesn't change by appending. An immutable object is an object that can change its contents with keeping identity (memory address). Roughly, an immutable object is simply a box or container. Even if contents in a box change, the box itself doesn't change.


Powered by Markdown