None constant is used to represent a null value, a missing value, or no value.
Setting a variable to None
To set a variable
None, just use the
>>> a = None >>> type(a) <class 'NoneType'>
None starts with uppercase N
None starts with capital
n does not work.
>>> a = none Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'none' is not defined. Did you mean: 'None'?
None (with uppercase
N) is a reserved word in Python. You can't assign anything to
>>> None = 123 File "<stdin>", line 1 None = 123 ^^^^ SyntaxError: cannot assign to None
On the contrary, you are free to name a variable
none (though this is not recommended as it may confuse human readers of your code).
>>> none = 123 >>> type(none) <class 'int'>
None and True/False
>>> bool(None) False
None equals neither
>>> None == False False >>> None == True False
Using is None vs. == None
To test whether a variable is
None, use the
is (identity) operator.
>>> a = None >>> a is None True
In most cases,
a is None works exactly the same as
a == None, but there may be cases when they behave differently (if the class of the variable
a custom implements the equality operator
__eq__() in an unusual way).
is is considerably faster than
==, which makes no practical difference for a single variable evaluation, but can have measurable effect when comparing a million variables to
Bottom line: Use
is None, unless you have a special reason to use
None vs. Nonetype
>>> type(None) <class 'NoneType'>
So there is a subtle difference: