Python String Immutability

Previous
Next

Immutability:

  • Python is Object oriented programming language.
  • Any information(Number, String or Collection) stores in Object format only.
  • Object behavior is either Mutable or Immutable.
  • Immutable objects : Numbers , Strings and Tuples
  • Mutable Objects : Lists, Sets and Dictionaries

Data types divided into Mutable and Immutable objects as follows:

  • If the object is immutable, state is fixed.
  • Immutable object cannot be modified.
  • Mutable objects cannot be fixed.
  • Immutable objects nothing but constants. We cannot modify the contents of Object once created.

Numbers:

  • Integers and Float values comes under Number type Objects.
  • Once we assign any number to a variable that cannot be modified.
  • If we try to modify the value, a new object will be creating with modified content.
a=10
print("a val :", a)
print("Loc :", id(a))

a=a+5
print("Modified a val :", a)
print("Loc :", id(a))

String Immutability:

s1="Hello"
s2="World"
print("s1 val :",s1)
print("s1 loc :",id(s1))
print("s2 val :",s2)
print("s2 loc :",id(s2))

s1=s1+s2
print("Modified s1 val :",s1)
print("s1 loc :",id(s1))
print("s2 val :",s2)
print("s2 loc :",id(s2))

When we try to create multiple String objects with the same content, duplicate objects will not be created. The address of object will be shared.

s1="Hello"
s2="Hello"
print("s1 val :",s1)
print("s1 loc :",id(s1))

print("s2 val :",s2)
print("s2 loc :",id(s2))
  • In the above code, both s1 & s2 objects pointing to same location.

Does s2 effects when we modify s1 content in the above code?

  • No, String object is Immutable. When the contents are same then only locations are same. When we modify the content, a new object will be created in another location.
s1="Hello"
s2="Hello"
print("s1 val :",s1)
print("s1 loc :",id(s1))
print("s2 val :",s2)
print("s2 loc :",id(s2))

s1 = s1+'$'
print("s1 val :",s1)
print("s1 loc :",id(s1))
print("s2 val :",s2)
print("s2 loc :",id(s2))
Previous
Next

Add Comment

Courses Enquiry Form