I just started with Python 3. In a Python book i read that the interpreter can be forced to make a copy of a instance instead creating a reference by useing the slicing-notation.
This should create a reference to the existing instance of s1:
s1 = "Test"
s2 = s1
print(s1 == s2)
print(s1 is s2)
This should create a new instance:
s1 = "Test"
s2 = s1[:]
print(s1 == s2)
print(s1 is s2)
When running the samples above both return the same result, a reference to s1.
Can sombody explain why it’s not working like described in the book? Is it a error of mine, or a error in the book?
This is true for mutable datatypes such as lists (i.e. works as you expect with
s1 = [1,2,3]).However strings and also e.g. tuples in python are immutable (meaning they cant be changed, you can only create new instances). There is no reason for a python interpreter to create copies of such objects, as you can not influence s2 via s1 or vice versa, you can only let s1 or s2 point to a different string.