I'm using Treehouse for Python basics and the tutor mentions this in the context of reassigning a value to a string variable. But if the value of the string variable can be reassigned, what does it mean to say it's immutable? Is there something I'm just not getting? Thanks.
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 to
a = a + a
# a points to the new string "FooFoo", but b still points to the old "Foo"
print a
print b
# Outputs:
# FooFoo
# Foo
# Observe that b hasn't changed, even though a has.
Videos
I think it could be very useful to have strings mutable. We could to this:
However, I guess there is a reason why strings are immutable. I wonder why?
str = 'apple' str[0] = 'A'
Why they made strings like this? What was the issue not creating them mutable like other iterables ie lists? Is it implemented intentionally in this way for some reason, or they made it like this due to some implementation issue ( it become compulsion on them to do it, or optimization issue )?