Immutable and Mutable in python
This article talks about concept of mutable and immutable object with detailed example
Immutable objects
Immutable object is the one whose value cannot be changed after it gets created. For example- String, Integer and tuple are immutable in python
Lets understand it by below example
create an integer name as “i” ad assign it a value “5”. Print its memory address using id() function provided by python.
i = 5
print("address of variable i after assigning it value 5 is ", id(i))
output is
Here “i” is a variable which is referring to an integer object whose value is 5 and memory address is 140704683530808
Now lets reassign the variable “i” with value “6” and check if same object gets updated or a new object gets created
Output is
As we can see after reassigning the integer variable, it actually creates new object (i.e. 6) but does not change the original object (i.e. 5) that is why we are getting different memory addresses for both objects (5 and 6).
Hence proved that Integer is immutable object :)
Mutable object
Mutable object is the one whose value can be changed after it gets created. e.g. List, dictionary
Lets understand it by below example
Create a list and print it’s memory address.
lst = [1,2]
print("data type of lst is ", type(lst))
print("address of lst after creating it ", id(lst))
output
Now lets update the code. First create a list and then update it by appending one more value in it and validate if same list object gets updated or new object gets created.
lst = [1,2]
print("data type of lst is ", type(lst))
print("address of lst after creating it ", id(lst))
#update the list by appending one more value in it
lst.append(3)
print("address of lst after updating it ", id(lst))
As we can see updated list’s address is same as it was before updating which implies that list object can be updated after creating it hence list is mutable