Object Identity Comparison

In addition to value comparisons, Python also supports the notion of directly comparing objects themselves. Objects can be assigned to other variables (by reference). Because each variable points to the same (shared) data object, any change effected through one variable will change the object and hence be reflected through all references to the same object.

In order to understand this, you will have to think of variables as linking to objects now and be less concerned with the values themselves. Let us take a look at three examples.

Example 1:

foo1 = foo2 = 4

When you look at this statement from the value point-of-view, it appears that you are performing a multiple assignment and assigning the numeric value of 4 to both the foo1 and foo2 variables. This is true to a certain degree, but upon lifting the covers, you will find that a numeric object with the contents or value of 4 has been created. Then that object’s reference is assigned to both foo1 and foo2, resulting in both foo1 and foo2 aliased to the same object.

Example 2:

foo1 = 4
foo2 = foo1

This example is very much like the first: A numeric object with value 4 is created, then assigned to one variable. When foo2 = foo1 occurs, foo2 is directed to the same object as foo1 since Python deals with objects by passing references. foo2 then becomes a new and additional reference for the original value. So both foo1 and foo2 now point to the same object.

Example 3:

foo1 = 4
foo2 = 1 + 3

This example is different. First, a numeric object is created, then assigned to foo1. Then a second numeric object is created, and this time assigned to foo2. Although both objects are storing the exact same value, there are indeed two distinct objects in the system, with foo1 pointing to the first, and foo2 being a reference to the second.Python provides the is and is not operators to test if a pair of variables do indeed refer to the same object. Performing a check such as

a is b

is an equivalent expression to

id(a) == id(b)

The object identity comparison operators all share the same precedence level and are presented in following Table.

Operator function
obj1 is obj2 obj1 is the same object as obj2
obj1 is not obj2 obj1 is not the same object as obj2


>>> a = [5,'hat',-9.3]
>>> b = a
>>> a is b
>>> a is not b
>>> b = 2.5e-5
>>> b
>>> a
[5, 'hat', -9.3]
>>> a is b
>>> a is not b

Both the is and not identifiers are Python keywords


You may also like...