0

As I know, immutability of object in python means that when we modify this object, new object being created in computer memory and new object's id and old_object's id are different. Then I can't understand, why when I create my string variable s = 'Dragon' and then adding a char, id is changing. But when I keep adding characters to string s, id is not changing. Why?

s = 'Dragon'
print(id(s))
s += 'a'
print(id(s), s)
s += 'b'
print(id(s), s)
s += 'c'
print(id(s), s)
140019146112112
140019146112240 Dragona
140019146112240 Dragonab
140019146112240 Dragonabc
jjjjake
  • 15
  • 4
  • The first `id` is constant for all string literals of `'Dragon'` (I believe this is called string interning, but I may be wrong). For the next, the id is probably constant since id is memory location and strings work like vectors (called lists in python) where a certain amount of memory is reserved past the end of the string to prevent extra copying being required for increasing the size slightly – Samathingamajig Apr 24 '22 at 20:18
  • 1
    IDs are not guaranteed to be unique for the lifetime of a Python program; they can get recycled when the object they point to is garbage-collected. Multiple different strings can therefore share the same ID, provided they don't all exist at the same time. – Samwise Apr 24 '22 at 20:18
  • 1
    "As I know, immutability of object in python means that when we modify this object, new object being created in computer memory" this is pretty much correct but contradictory, immutability means **you cannot modify the object** and if it *looks* like the API does that, it is actually resulting in a new object – juanpa.arrivillaga Apr 24 '22 at 20:23
  • s += 'c' is parsed as `s = s + c` which is just creating a "new" object rather than mutating the original object. to mutate, try `s[0] = "a"` for example – Onyambu Apr 24 '22 at 20:26
  • @Samathingamajig no, strings aren't "vectors" (what would be the *point* in an immutable data structure) and even if it did, that would explain the behavior here since it is the memory address of the PyObject head which is just the standard head of any object (a reference count and a type pointer) – juanpa.arrivillaga Apr 24 '22 at 20:28

0 Answers0