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?
In Python, strings are made immutable so that programmers cannot alter the contents of the object (even by mistake).
In python, the string data types are immutable. Which means a string value cannot be updated.
The String is immutable, so its value cannot be changed. If the String doesn't remain immutable, any hacker can cause a security issue in the application by changing the reference value. The String is safe for multithreading because of its immutableness.
It violates the rules of how ID values and += are supposed to work - the ID values produced with the optimization in place would be not only impossible, but prohibited, with the unoptimized semantics - but the developers care more about people who would see bad concatenation performance and assume Python sucks.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With