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?
Course: https://www.educative.io/courses/python-fundamentals-for-programmers
Lesson: https://www.educative.io/courses/python-fundamentals-for-programmers/JYJMP8Y2WlK