There is some code:
import copy a = 'spamlkfna;inoianoiho' b = copy.copy(a) if a is b: print("yes")
In the book that I am reading, I found out that 2 variables are being created here that will refer to different objects, but the string if a is b returns True. I can not understand why this happens if is returns true only if the 2 links are equal, that is, they refer to the same object. Is it all optimization tricks? Or in the version after python 3.0 this moment looks different? My version on which I work 3.7.1
b = a[:]
is a short and beautiful analogue ofcopy.copy(a)
, based on the fact that the slice returns a shallow copy of the data. For a string, it also returns a reference to the interned instance, but for a list of characters it will work. - Sergey Gornostaev