A useful tidbit to add to people's understanding.
The reason that we check for identity with None
is because Python only ever stores the value None
in one place in memory, and every object which equals None
has its value stored in this same location. There are a handful of "special values" which get this treatment, and None
is just one of them.
But most values do not get this special treatment! For example, the float 1.25 can be stored in different locations in memory:
a = None
b = None
a is b
True
a = 1.25
b = 1.25
a is b
False
It just so happens that None
is among the handful of values which are always stored in one place in memory. Another example is any integer between -5
and 256
... since these integers are used often, they are always stored in memory, and every integer with that value is stored in the same place in your computer's memory! Try it out:
a = 256
b = 256
a is b
True
a = 257
b = 257
a is b
False
So you can think of None
as being part of a special class of values which always have a constant memory address. That is why we can use is
to check whether two variables are both None
... it just checks whether the memory address is the same.
Edit: Joooeey makes the good point that which integers are stored in memory is specific to your python implementation, and the example of numbers from -5
to 256
is specific to CPython. If you don't know what you're running, it's probably CPython, which is the most common implementation. But for this reason (and others) it is better practice to compare equality between these numbers with a == 2
and not with a is 2
. As for None
, it is specified to be the sole instance of the NoneType
type according to the Python Documentation itself, so regardless of implementation you can always compare it using a is None
.
is
- python.org/dev/peps/pep-0008/#programming-recommendations – Paralyse