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.
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.
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.
== operator is used to check whether two variables reference objects with the same value.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With