Reading Time: 1 minutes
Equality & Identity in Python
While comparing two objects, there are two things to consider. One, whether the two objects refer to the same object in memory. Second, whether the values held by the two objects are the same.
To verify if two objects refer to the same object in memory, you can use the builtin id() function or use the is operator. The builtin id() function gives the "identity" of an object i.e. an integer which is guaranteed to be unique and constant for this object during its lifetime. Python's help() function suggests that the id() function returns the object's memory address. No two objects in the same program lifecycle can have the same id() value.
>>> objOne = 'This is a string.' >>> objTwo = objOne >>> objThree = 'This is a string.' >>> objOne is objTwo True >>> objOne is objThree False >>> id(objOne) 49223224 >>> id(objTwo) 49223224 >>> id(objThree) 49218208 >>> id(objOne) == id(objTwo) True >>> id(objOne) == id(objThree) False >>>
To check whether the values held by the two objects are equal, you can use the == operator.
>>> objOne = 'This is a string.' >>> objTwo = objOne >>> objThree = 'This is a string.' >>> >>> objOne == objTwo True >>> objOne == objThree True