Difference between revisions of "Identity vs. equality"

 [checked revision] [checked revision]

In Python, identity is different from equality.

Equality (==)

x == y is true if and only if x and y have the same value. Example:

>>> x = (1, 2, 3)
>>> y = (1, 2, 3)
>>> x == y
True
>>> x = 1.0
>>> y = 1.0
>>> x == y
True

Two functions/methods are == if and only if they are is. Example:

>>> class A:
...     def fn(self):
...         pass
...
>>> a1 = A()
>>> a2 = A()
>>> a1.fn is a2.fn
False
>>> a1.fn == a2.fn
False

Identity (is, is not)

x is y is true if and only if x and y point to the same object in memory. Usually, identity (is) implies equality (==). Example:

>>> a = [1, 2, 3]
>>> b = a
>>> a is b
True
>>> a == b
True

An identity test is more stringent than an equality test since two distinct objects may have the same value. Example:

>>> x = [1, 2, 3]
>>> y = [1, 2, 3]
>>> x == y
True
>>> x is y
False

For the built-in immutable types (e.g., int, str and tuple), Python uses caching to improve performance (the interpreter may decide to reuse an existing immutable object instead of creating a new one with the same value). For example, Python caches integers in the range [-5, 256], so we get the following:

>>> x = 256
>>> y = 256
>>> x is y
True
>>> x = 257
>>> y = 257
>>> x is y
False
The lesson is: when comparing integers in Python, always use ==.