Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 715
snakile Avatar asked Sep 05 '10 19:09

snakile


People also ask

How do you check if two variables point to the same object in Python?

The is keyword is used to test if two variables refer to the same object. The test returns True if the two objects are the same object. The test returns False if they are not the same object, even if the two objects are 100% equal. Use the == operator to test if two variables are equal.

How do you know if two objects have the same reference?

For reference type like objects, == or === operators check its reference only. here a==b will be false as reference of both variables are different though their content are same. and if i check now a==b then it will be true , since reference of both variable are same now.

Which operators can be used to determine whether two variables are referring to the same object or not?

== operator is used to check whether two variables reference objects with the same value.

How do you check if an object has equality in Python?

Every object has an identity, a type and a value. == and is are two ways to compare objects in Python. == compares 2 objects for equality, and is compares 2 objects for identity.


1 Answers

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 
like image 135
Mark Byers Avatar answered Oct 18 '22 15:10

Mark Byers