About string copy

I did some research online and found that using slicing to copy the content of string into string_cpy should work fine. However when I tried to run the code below, the result surprised me.

string = "This is MY string!"
string_cpy = string[:]
print(id(string) == id(string_cpy))     # True ???!!!
string_cpy = 'copy'
print(string)       # This is MY string!
print(string_cpy)   # copy
print(id(string) == id(string_cpy))     # False

The last four lines of code demonstrate the correctness – modifying the content of string_cpy does not affect the content of string itself, and the last line also reflects that string and string_cpy have different memory locations.

But what surprised me is the result of the third line, why is it True? Even though string and string_cpy point to different objects, why do they have the same identifier value?


Hello @PUPU

string = "This is MY string!"
string_cpy = string[:]
print(id(string) == id(string_cpy))  # True ???!!!

You are slicing the string using string[:] , which creates a new string object containing the entire content of the original string .

However, it is important to note that Python has a string interning feature that optimizes memory usage for string literals. Python automatically interns small strings. When a string is interned, Python stores it in a special cache and reuses the same object if the same string literal is used again. This optimization reduces memory usage and improves performance for commonly used strings.

The reason id(string) == id(string_cpy) returns True is due to string interning. The original string and the sliced string_cpy are two separate string objects in memory, but since Python doesn’t intern the long strings, they have different objects but the same identifier value. This behavior is specific to string interning. The key point here is that Python does not intern the new string but keeps the original string interned. Since the original string is interned, it has the same identifier value as the new sliced copy. That’s why id(string) == id(string_cpy) returns True .

I hope this will help.
Happy Learning