Concept of Mutable & Immutable objects in Python

An Immutable object, in the lime light of object-oriented and functional programming, is an object whose state cannot be modified after it is created.

Objects of built-in types like (intfloatboolstrtupleunicode) are immutable,

Mutable object, can be mutated or state can be modified after it is created. A mutable object will have at least a single method able to mutate the object.

Objects of built-in types like (listsetdict) are mutable, Custom classes are generally mutable. To simulate immutability in a class, one should override attribute setting and deletion to raise exceptions:

Please refer “names concept” in python, if you don’t have a clear concept onobjects,identifier, `variables.

A practical example to findout the mutablity of object types

x = 10
x = y

We are creating an object of type int. identifiers x and y points to the same object.

id(x) == id(y)
id(y) == id(10)

if we do a simple operation.

x = x + 1

Now

id(x) != id(y)
id(x) != id(10)

The object in which x was tagged is changed. object 10 was never modified. Immutable objects doesn’t allow modification after creation

In the case of mutable objects

m = list([1, 2, 3])
n = n

We are creating an object of type list. identifiers m and m tagged to the same list object, which is a collection of 3 immutable int objects.

id(m) == id(n)

Now poping an item from list object does change the object,

m.pop()

object id will not be changed

id(m) == id(n)

m and n will be pointing to the same list object after the modification. the list object will now contain [1, 2]

Unexpected results can be expected if you use mutable objects in

  • Function’s default arguments
  • Class inheritance

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top