I have been reading the Python Data Model. The following text is taken from here:
Types affect almost all aspects of object behavior. Even the importance of object identity is affected in some sense: for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed. E.g., after
a = 1; b = 1
,a
andb
may or may not refer to the same object with the value one, depending on the implementation, but afterc = []; d = []
,c
andd
are guaranteed to refer to two different, unique, newly created empty lists. (Note thatc = d = []
assigns the same object to bothc
andd
.)
So, it mentions that, for immutable types, operations that compute new values may actually return a reference to an existing object with same type and value. So, I wanted to test this. Following is my code:
a = (1,2,3)
b = (1,2)
c = (3,)
k = b + c
print(id(a))
>>> 2169349869720
print(id(k))
>>> 2169342802424
Here, I did an operation to compute a new tuple that has same the value and type as a
. But I got an object referencing to different id. This means I got an object which references different memory than a. Why is this?