Does an immutable object in python mean that its value cannot be changed after its conception? If that is the case what will happen when we try to change its value.
Let me try to explain my doubt with an example.
For instance I initialized a String object S
with value "Hello World"
.
S = 'Hello World'
Then I typed in the line,
S = 'Hello Human'
So when I ask the interpreter, it tells me the value of S is "Hello Human"
. Clearly now 'S' has a new value.
How did the value change? Did python destroy the old string object and created a new one with the new value? or did it just changed the value of the old object. Does this has anything to do with the fact that the string object is immutable? If so, then how do mutable objects behave?
The immutable objects are objects whose value can not be changed after initialization. We can not change anything once the object is created. For example, primitive objects such as int, long, float, double, all legacy classes, Wrapper class, String class, etc. In a nutshell, immutable means unmodified or unchangeable.
An Immutable Object means that the state of the Object cannot change after its creation. Here the String is immutable means that you cannot change the object itself, but you can change the reference to the object.
Immutable is the when no change is possible over time. In Python, if the value of an object cannot be changed over time, then it is known as immutable. Once created, the value of these objects is permanent.
An immutable object is an object that is not changeable and its state cannot be modified after it is created. In Python, a string is immutable. You cannot overwrite the values of immutable objects. However, you can assign the variable again.
Python stopped S
pointing to the the old string object and made it point to a new one
>>> S="Hello World"
>>> id(S)
32386960
>>> S="Hello Human"
>>> id(S)
32387008
>>>
You can't change immutable objects, so even when you think you muight be (eg with the +=
operator) you aren't
>>> S="Hello"
>>> id(S)
32386912
>>> S+=" World"
>>> id(S)
32386960
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With