How do I check if two variables reference the same object in Python?

徘徊边缘 提交于 2019-11-30 05:36:12

You can use is to check if two objects have the same identity.

>>> x = [1, 2, 3]
>>> y = [1, 2, 3]
>>> x == y
True
>>> x is y
False

To build on the answer from Mark Byers:

The is evaluation to distinguish identities will work when the variables contain objects and not primitive types.

object_one = ['d']
object_two = ['d']
assert object_one is object_two  # False - what you want to happen

primitive_one = 'd'
primitive_two = 'd'
assert primitive_one is primitive_two  # True - what you don't want to happen

If you need to compare primitives as well, I'd suggest using the builtin id() function.
From the Python docs:

Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime.

So that will become this:

assert id(primitive_one) == id(primitive_two)  # False
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!