Hit enter after type your search item

What is ‘None’ – the equivalent of Null in Python?

Declaring variables as null or evaluating an expression as null in if condition (or other cases) is quite common practice as doing programming in different languages.

This is generally done by using the keyword ‘null’. However, in Python, there is no such keyword as null. Instead, you may use the ‘None’ keyword, which is an object. This is how you may assign the ‘none’ to a variable in Python:

ex_none = None

None in if statement example None in List None is Set

Note: The first letter in ‘None’ keyword is the capital N. The small ‘n’ will produce an error.

In other programming languages, for example, this is how you may create a null variable in PHP and Java:

In Java:

myVariable = null;

In PHP:

$myVariable = NULL;

If you need to evaluate a variable in the if condition, you may check this as follows in Java:


See the examples below for learning how to use the ‘None’ in Python. I will use it in the if statement and a few compound data types.

An example of using none variable in the if statement

First of all, a variable is declared with the none value in the example. After assigning the value, we will check if it is none.

In the if statement, you may use the identity operator ‘is’ as follows:

Tip: The ‘is’ and ‘is not’ are two identity operators supported in Python for comparing the memory locations of two objects.

Python null

See online demo and code


The output of the above example is:

The value of the variable is none

Using the == operator example for Python Null

Rather than using the identity operator in the if statement, you may also use the comparison operators like ==, != etc. for evaluating a ‘none’ value. See the example with the code below where same code is used as in above example except the comparison operator:

See online demo and code


 

The output of this example is the same as in above example.

An example of using None/Null in a Set

In this example, a Python set is created with a few items. The second item is given the ‘None’ value. A for loop is used to display the set items and finally the length of the set is displayed. See the code and output by clicking the link below:

none in Python example

See online demo and code


 

You can see, the None is displayed while the length of the set includes the None item as well.

Using None value in a List example

Similarly, you may use the Null value in the compound data type List. Just use the None keyword as in case of sets.

See this example where I have created a list and the third item in the list is None keyword:

null list

See online demo and code


 

See the code and output on the example page.

Note that, the None is an object so you may not use it for checking if the variable exists or not.

This div height required for enabling the sticky sidebar