Why (not how) python primitive data types like int and string are immutable. Is that because of a implementation limitation of scripting language.
as a example
a = 5;
a = 6;
in second line(a = 6;) instead of creating a new memory location, why cant it change the first memory location to 6
Some Python data types are immutable because Python uses reference/pointer semantics.
This means that whenever you assign an expression to a variable, you're not actually copying the value into a memory location denoted by that variable, but you're merely giving a name to the memory location where the value actually exists.
Now, if for example strings were mutable, this would happen:
a = "test"
b = a
b[2] = "o"
# Now a would be "tost", oops.
This behaviour was considered unintuitive, so strings were made immutable.
Similarly for integers, if assigning a new value would change the original location, the following would happen:
a = 5
b = a
b += 5
# a is now 10 :(
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