# Difference between revisions of "Identity vs. equality"

From CS 61A Wiki

[checked revision] | [checked revision] |

m ({{Sufficient-class}}) |
m (→Equality (==): make instance method) |
||

(One intermediate revision by one user not shown) | |||

Line 13: | Line 13: | ||

>>> x == y | >>> x == y | ||

True | True | ||

+ | </syntaxhighlight> | ||

+ | |||

+ | Two functions/methods are <code>==</code> if and only if they are <code>is</code>. Example: | ||

+ | <syntaxhighlight lang="python"> | ||

+ | >>> class A: | ||

+ | ... def fn(self): | ||

+ | ... pass | ||

+ | ... | ||

+ | >>> a1 = A() | ||

+ | >>> a2 = A() | ||

+ | >>> a1.fn is a2.fn | ||

+ | False | ||

+ | >>> a1.fn == a2.fn | ||

+ | False | ||

</syntaxhighlight> | </syntaxhighlight> | ||

## Latest revision as of 22:57, 5 June 2014

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

`==`

.