Chapter 2: Object Identity

Identity operators

face Josiah Wang

You can use the identity operators (is, is not) to check whether two variables/literals refer to the same object.

>>> x = complex(2, 4)
>>> y = complex(2, 4)
>>> id(x)
140613669720208
>>> id(y)
140613670158096
>>> x is y
False
>>> x is not y
True

In a nutshell, x is y checks whether id(x) == id(y).

If x is y is True, then it implies that x == y is also True. Obviously, the same object must have the same value.

However, the reverse is not true. Just because two objects are equal does not necessarily mean they refer to the same object. Remember that the behaviour of == can change depending on the operand (e.g. 5 == 5.0 is True, but they are not the same object!) The behaviour can even be customised by the programmer!

Try the following to convince yourself!

>>> x = [1, 2, 3, 4, 5]
>>> y = [1, 2, 3, 4, 5]
>>> print(x == y)
True
>>> print(x is y)
False

In this case, x and y have the same value, but they are different objects. You can modify x later and y will not be affected.