Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare if two variables reference the same object in python

Tags:

python

How to check whether two variables reference the same object?

x = ['a', 'b', 'c'] y = x                 # x and y reference the same object z = ['a', 'b', 'c']   # x and z reference different objects 
like image 276
pic11 Avatar asked Mar 26 '11 20:03

pic11


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.

Can two variables refer to the same object?

Yes, two or more references, say from parameters and/or local variables and/or instance variables and/or static variables can all reference the same object.

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.


1 Answers

That’s what is is for.

In the example, x is y returns True because it is the same object while x is z returns False because it are different objects (which happen to hold identical data).

like image 98
Jochen Ritzel Avatar answered Oct 28 '22 20:10

Jochen Ritzel