[Solved] Clarification needed regarding immutability of strings in Python [closed]


In CPython, ids relate to where in memory the string is stored. It does not indicate anything about mutability. How memory is used exactly is an internal implementation detail. You could of course do a deep dive into the internals of CPython’s memory management to disentangle that in-depth, but that’s not really useful. (Im)mutability can simply be demonstrated:

>>> foo = 'bar'
>>> baz = foo
>>> id(foo), id(baz)
(4402654512, 4402654512)
>>> foo += 'quux'
>>> print(foo, baz)
barquux bar
>>> foo[1] = 'o'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

Altering foo using += does not mutate baz, even though they used to refer to the same object. Altering a character directly though subscription (foo[1] = ...) does not work and raises an error. This demonstrates string immutability. How memory is allocated for this during execution is not really relevant.

solved Clarification needed regarding immutability of strings in Python [closed]