同一列表中的Python ID不相等


x = [1,2,3]
y = x
print(id(x))
print(id(y))
print(id(x) == id(y))
print(id(x) is id(y))

输出:

140181905497736
140181905497736
True
False

当x和y的ID相同时,为什么第二个是错误的?

进行id(x) is id(y)时,您正在比较对象整数身份的身份,而不是列表对象本身的身份。作为实现细节,整数仅在-5256的范围内在CPYTHON中缓存。id(x) == id(y)当然可以按预期执行return True,因为x is y return S True

您看到了这一点,因为在第一个比较中,您比较了两个对象的身份,但是在第二个对象中,您比较了由 id()生成的两个新对象功能。此示例您可以帮助您更好地理解:

# Here you can see that a and b are indeed the same
>>> a = [1,2,3]
>>> b = a
>>> a is b
True
>>> id(a) == id(b)
True
# Now lets store id(a) and id(b). Their values should still be the same
>>> A = id(a)
>>> A
4319687240
>>> B = id(b)
>>> B
4319687240
>>> A == B
True
# But A and B are separate objects. Which is what you compare in the second comparison 
>>> id(A)
4319750384
>>> id(B)
4319750544
>>> id(a) is id(b)
False
>>> A is B
False
# You can also see this at play if you try to print id of another id
>>> print(id(id(a)))
4319750416
>>> print(id(id(a)))
4319750512

最新更新