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

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


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.


The string objects themselves are immutable.

The variable, a, which points to the string, is mutable.

Consider:

a = "Foo"# a now points to "Foo"b = a# b points to the same "Foo" that a points toa = a + a# a points to the new string "FooFoo", but b still points to the old "Foo"print aprint b# Outputs:# FooFoo# Foo# Observe that b hasn't changed, even though a has.


The variable a is pointing at the object "Dog". It's best to think of the variable in Python as a tag. You can move the tag to different objects which is what you did when you changed a = "dog" to a = "dog eats treats".

However, immutability refers to the object, not the tag.


If you tried a[1] = 'z' to make "dog" into "dzg", you would get the error:

TypeError: 'str' object does not support item assignment" 

because strings don't support item assignment, thus they are immutable.