Why do different strings have the same ID in Python?

Viewed 1524

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?

1 Answers

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.

Related