具有相同值和类型的不可变对象不引用相同的对象

Immutable objects with same value and type not referencing same object

我一直在阅读 Python 数据模型。以下文字摘自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.)

因此,它提到,对于不可变类型,计算新值的操作实际上可能 return 对具有相同类型和值的现有对象的引用。所以,我想测试一下。以下是我的代码:

a = (1,2,3)
b = (1,2)
c = (3,)
k = b + c
print(id(a))
>>> 2169349869720    
print(id(k))
>>> 2169342802424

在这里,我做了一个操作来计算一个与 a 具有相同值和类型的新元组。但是我得到了一个引用不同 id 的对象。这意味着我得到了一个引用不同内存的对象。这是为什么?

根据@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.