Strings are immutable, and after creating a string, it can no longer be changed.
foo and, more importantly, baz are both lines. This means that when they are created, they fall into memory and can no longer be changed.
Once you assigned foo = bar , you created this object and assigned it to a specific location in memory. The same thing was done with baz .
Even if baz was like a string literal format , it does not mean that it is no longer immutable, because:
In [4]: type(baz) Out[4]: str
Thus, baz was created as an object and assigned to your memory as Hanging on in bar , so its relation to foo is pure during instance creation. During which baz searches for the foo object and concatenates it when necessary.
Once you created foo = 'spam' , you destroyed the original destination foo and created a new one in memory.
Leb
source share