How to check if two variables refer to the same object in Python?

x and y are two variables.
I can check if they are 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 are not the same object.
I am looking for something like sameObject(x, y) which in this case should be false.

+38
python equality
Sep 05 '10 at 19:54
source share
2 answers

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

 >>> x = [1, 2, 3] >>> y = [1, 2, 3] >>> x == y True >>> x is y False 
+52
Sep 05 '10 at 19:56
source share

To build an answer from Mark Byers:

is evaluation of distinguishing between identities will work when variables contain objects, 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, I would suggest using the built-in id() function.
From Python docs :

Return the "identity" of the object. This is an integer that is guaranteed to be unique and constant for this object throughout its life.

So it will be like this:

 assert id(primitive_one) == id(primitive_two) # False 
+1
Feb 01 '19 at 16:13
source share



All Articles