Table of content

Mutability in Python

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 l=[30,35,40]

here l is the reference variable, and an object contains 30,35 and 40 and prints its address by using the id() function print(id(l))

If I am going to change the content of the list as l[0] =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[0]=12
print(id(l))
print(l[0])
print(l)

mutability-example-one

Let us consider another one example; here I am using L1 and L2 where L1=[45,60,70] and L2=L1 that means both the reference values are pointing to the same object if you print(l1) and 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)

taking-lone-and-ltwo

If I am changing the content of the L1[0]=15 and then trying to print once again print(l1) and print(l2) in both cases L1[0] 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[0]=15
print(L1)
print(L2)

changing-lone-value

Now I am trying to change the value of L2[1]=20 then, if you print(l1) and print(l2) then in both cases, the value 60 has been changed to 20

L2[1]=20
print(L1)
print(L2)

changing-the-ltwo-value

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions