I\'ve tried to understand when Python strings are identical (aka sharing the same memory location). However during my tests, there seems to be no obvious explanation when tw
In Example 2 :
# Example 2
s1 = "Hello" * 3
s2 = "Hello" * 3
print(id(s1) == id(s2)) # True
Here the value of s1 and s2 are evaluated at compile time.so this will return true.
In Example 3 :
# Example 3
i = 3
s1 = "Hello" * i
s2 = "Hello" * i
print(id(s1) == id(s2)) # False
Here the values of s1 and s2 are evaluated at runtime and the result is not interned automatically so this will return false.This is to avoid excess memory allocation by creating "HelloHelloHello" string at runtime itself.
If you do intern manually it will return True
i = 3
s1 = "Hello" * i
s2 = "Hello" * i
print(id(intern(s1)) == id(intern(s2))) # True