Aren't Python strings immutable? Then why does a + " " + b work?

jason picture jason · Feb 1, 2012 · Viewed 124.9k times · Source

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?

Answer

Bort picture Bort · Feb 1, 2012

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.