Fix Python – Aren’t Python strings immutable? Then why does a + ” ” + b work?

Question

Asked By – jason

My understanding was that Python strings are immutable.

I tried the following code:

a = "Dog"
b = "eats"
c = "treats"

print a, b, c
# Dog eats treats

print a + " " + b + " " + c
# Dog eats treats

print a
# Dog

a = a + " " + b + " " + c
print a
# Dog eats treats
# !!!

Shouldn’t Python have prevented the assignment? I am probably missing something.

Any idea?

Now we will see solution for issue: Aren’t Python strings immutable? Then why does a + ” ” + b work?


Answer

First a pointed to the string “Dog”. Then you changed the variable a to point at a new string “Dog eats treats”. You didn’t actually mutate the string “Dog”. Strings are immutable, variables can point at whatever they want.

This question is answered By – Bort

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0