Mutability : Everything in python is treated as an Object, and an object mutability is determined by its data type, and some of these data types are Mutable in python, which means we can change the content of the object without changing its identity.
Example: List, Dict and Set data types are Mutable data types
Let us understand Mutability through an example, consider a list contains some number
here l is the reference variable, and an object contains 30,35 and 40 and prints its address by using the id() function
If I am going to change the content of the list as
l =12, that means the value 30 has been replaced with 12 in the existing object only and
If the is mutable then, when you are going to print the address again, it should print the same id value
l=[30,35,40] print(id(l)) l=12 print(id(l)) print(l) print(l)
Let us consider another one example; here I am using L1 and L2 where
L2=L1 that means both the reference values are pointing to the same object if you
print(l2) then in both cases, you are going to get the same content values.
L1=[45,60,70] L2=L1 print(l1) print(l2)
If I am changing the content of the
L1=15 and then trying to print once again
print(l1) and print(l2) in both cases
L1 Value has been updated to 15, which means if I made any changes in L1, then it will be reflected in L2. Also, this behavior is called mutability.
L1=15 print(L1) print(L2)
Now I am trying to change the value of
L2=20 then, if you
print(l2) then in both cases, the value 60 has been changed to 20
L2=20 print(L1) print(L2)