Nayana Adassuriya
Nayana Adassuriya

Reputation: 24766

"Why" python data types are immutable

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

Upvotes: 5

Views: 1770

Answers (1)

orlp
orlp

Reputation: 117681

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 :(

Upvotes: 8

Related Questions