Python None Constant

Python 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 None keyword.

>>> a = None
>>> type(a)
<class 'NoneType'>

None starts with uppercase N

None starts with capital N. Lowercase 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.

>>> 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

In boolean operations, None evaluates to False.

>>> bool(None)

But None equals neither False nor True.

>>> None == False
>>> None == True

Using is None vs. == None

To test whether a variable is None, use the is (identity) operator.

>>> a = None
>>> a is None

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).

Moreover, 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 None.

Bottom line: Use is None, unless you have a special reason to use == None.

None vs. Nonetype

The None constant has its own special data type NoneType.

>>> type(None)
<class 'NoneType'>

So there is a subtle difference:

By remaining on this website or using its content, you confirm that you have read and agree with the Terms of Use Agreement.

We are not liable for any damages resulting from using this website. Any information may be inaccurate or incomplete. See full Limitation of Liability.

Content may include affiliate links, which means we may earn commission if you buy on the linked website. See full Affiliate and Referral Disclosure.

We use cookies and similar technology to improve user experience and analyze traffic. See full Cookie Policy.

See also Privacy Policy on how we collect and handle user data.

© 2024 PyTut