How do I check if two variables reference the same

2019-02-03 23:14发布

x and y are two variables.
I can check if they're equal using x == y, but how can I check if they have the same identity?

Example:

x = [1, 2, 3]
y = [1, 2, 3]

Now x == y is True because x and y are equal, however, x and y aren't the same object.
I'm looking for something like sameObject(x, y) which in that case is supposed to be False.

2条回答
叛逆
2楼-- · 2019-02-03 23:53

To build on the answer from Mark Byers:

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

object_one = ['d']
object_two = ['d']
assert thing_one is thing_two  # False

primitive_one = 'd'
primitive_two = 'd'
assert primitive_one is primitive_two  # True

If you need to comparte 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.

查看更多
Bombasti
3楼-- · 2019-02-03 23:53

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
查看更多
登录 后发表回答