Nicholas Liu Nicholas Liu - 4 months ago 8
Python Question

In Python, is None a unique object?

In my test code, why the

print
results for tuple and None are different? It seems that a, b point to the same object
None
, but c, d point to different objects, though their values are the same (both equal to
(a,b)
).

I know that
is
keyword checks for the object lying behind rather than just compares value like
==
. And here I use tuple because I think tuple is immutable so that at least it's not a matter of whether the object is mutable or immutable.

But why variables a, b don't create and point to two different
None
objects as c, d do to tuple?

a=None
b=None
c=(1,2)
d=(1,2)
print(a is b)
print(c is d)

Answer

None is a singleton object: only one instance of it can ever exist. So objects referencing None will always have the same identity, and two or more of such objects will always pass the identity (object equality) test:

>>> a = None
>>> b = None
>>> c = None
>>> a is b is c
True

Same applies to True and False

>>> d = True
>>> (a is b is c) is d # proof of concept only
True
Comments