9

It is stated that strings are immutable objects, and when we make changes in that variable it actually creates a new string object.

So I wanted to test this phenomenon with this piece of code:

result_str = ""

print("string 1 (unedited):", id(result_str))

for a in range(1,11):
    result_str = result_str + str(a)
    print(f"string {a+1}:", id(result_str))

And I got the following IDs:

string 1 (unedited): 2386354993840
string 2: 2386357170336
string 3: 2386357170336
string 4: 2386357170336
string 5: 2386357170336
string 6: 2386357170336
string 7: 2386357170336
string 8: 2386357170336
string 9: 2386360410800
string 10: 2386360410800
string 11: 2386360410800

So, if each string is different from each other, then why do the strings 2-8 and 9-11 have the same ID? And, if somehow this question is explained why does the ID change at string 9 specifically?

Paolo
  • 21,270
  • 6
  • 38
  • 69
Frenk Frenk
  • 113
  • 7
  • 6
    I don't know at what point the old and new `result_str` are destroyed and created and if they overlap in their lifetime, but the Python docs says "Two objects with non-overlapping lifetimes may have the same id() value." – Feodoran Jun 18 '20 at 15:15
  • 2
    why it changes at 9 is machine dependent, in my computer all the values have the same id. My guess is python allocates the memory to original string, then when that string is deleted that id is emptied and ready to use. Since it's first in the stack, it gets assigned to the next variable. but sometime it uses some other memory location. – Osman Mamun Jun 18 '20 at 15:52

1 Answers1

4

The string you associate with result_str create reaches end of lifetime at the next assignment. Hence the possibility of duplicate id.

Here's the doc

Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

Paolo
  • 21,270
  • 6
  • 38
  • 69
Balaji Ambresh
  • 4,977
  • 2
  • 5
  • 17