How does the is
operator determine if two objects are the same? How does it work? I can't find it documented.
From the documentation:
Every object has an identity, a type and a value. An object’s identity never changes once it has been created; you may think of it as the object’s address in memory. The ‘is‘ operator compares the identity of two objects; the id() function returns an integer representing its identity (currently implemented as its address).
This would seem to indicate that it compares the memory addresses of the arguments, though the fact that it says "you may think of it as the object's address in memory" might indicate that the particular implementation is not guranteed; only the semantics are.
Is works by comparing the object referenced to see if the operands point to the same object.
>>> a = [1, 2]
>>> b = a
>>> a is b
True
>>> c = [1, 2]
>>> a is c
False
c
is not the same list as a
therefore the is
relation is false.
is
in Python is for comparing singletons, like if foo is None
or sentinel = object() ... if bar is sentinel
. –
Quotation a.append(v)
will modify c. –
Auroora To add to the other answers, you can think of a is b
working as if it was is_(a, b)
:
def is_(a, b):
return id(a) == id(b)
Note that you cannot directly replace a is b
with id(a) == id(b)
, but the above function avoids that through parameters.
© 2022 - 2024 — McMap. All rights reserved.
==
between objects in Java. – Miyamoto