pythonimmutabilitypython-object

Immutable objects with same value and type not referencing same object


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 and b may or may not refer to the same object with the value one, depending on the implementation, but after c = []; d = [], c and d are guaranteed to refer to two different, unique, newly created empty lists. (Note that c = d = [] assigns the same object to both c and d.)

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?


Solution

  • Answering the question based on comments from @jonrsharpe

    Note "may actually return" - it's not guaranteed, it would likely be less efficient for Python to look through the existing tuples to find out if one that's the same as the one your operation creates already exists and reuse it than it would to just create a new one.