Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Why" python data types are immutable

Tags:

python

memory

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

like image 853
Nayana Adassuriya Avatar asked Mar 16 '23 13:03

Nayana Adassuriya


1 Answers

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 :(
like image 148
orlp Avatar answered Mar 26 '23 02:03

orlp