Mutable vs Immutable Objects in Python

Objects of built-in types like (int, float, bool, str, tuple, unicode) are immutable. Objects of built-in types like (list, set, dict) are mutable. Custom classes are generally mutable. To simulate immutability in a class, one should override attribute setting and deletion to raise exceptions.

ID and TYPE

''' Example 1 '''
>>> x = "Holberton"
>>> y = "Holberton"
>>> id(x)
140135852055856
>>> id(y)
140135852055856
>>> print(x is y) '''comparing the types'''
True
''' Example 2 '''
>>> a = 50
>>> type(a)
<class: ‘int’>
>>> b = "Holberton"
>>> type(b)
<class: 'string'>

Mutable and Immutable Objects

Mutable objects:

list, dict, set, byte array

Immutable objects:

int, float, complex, string, tuple, frozen set [note: immutable version of set], bytes

x = 10x = y
id(x) == id(y)id(y) == id(10)
x = x + 1
id(x) != id(y)id(x) != id(10)
m = list([1, 2, 3])n = m
id(m) == id(n)
m.pop()
id(m) == id(n)

Exceptions in immutability..

How objects are passed to Functions

def updateList(list1):
list1 += [10]
n = [5, 6]
print(id(n)) # 140312184155336
updateList(n)
print(n) # [5, 6, 10]
print(id(n)) # 140312184155336
def updateNumber(n):
print(id(n))
n += 10
b = 5
print(id(b)) # 10055680
updateNumber(b) # 10055680
print(b) # 5

--

--