Data Types - None


In this tutorial you will learn all about the None object in Python.


Python None Explained

None is an object frequently used to represent the absence of a value - null. NoneType is the type for the None object. It is noteworthy that None is the sole instance of the NoneType class. Therefore, you can check if value is None by comparing it to None using the is operator.

It is important to notice that:

  • None is not 0.
  • None is not an empty string.
  • None is not the same as False (although it is evaluated the same).

Since None is a keyword in Python (reserved word), assignments to None are illegal and raise syntax errors.

When is None object used?

Python None is used to indicate that there is no value and frequently used to represent the absence of a value. Here are some examples:

  • Functions with no return statement return None.
  • None can be useful as a sentinel value (flag value).
  • None is also used to indicate that when default parameters are not supplied while calling a function.

Here is an example:

#NoneType last_item = None my_list = [] for i in my_list: last_item = i print (last_item)

How to check if a value is None in Python
(compare to None)

None is a singleton object - a sole instance of the NoneType class. Therefore, you should prefer to use the “is” operator in order check if a value is None. The “is” operator returns True when two values point to the same object (are identical). It is also possible to use the == operator, which returns True when two values are equal.

Here is an example:

#NoneType x = None print(type(x)) print("None is None ", None is None) print("is None == None ", None == None) print("is None == 0 ", None == 0) print("is None == x ", None == x)

Python none vs null

The first thing to know is there is no null keyword in Python. Instead of null, the None keyword is used in Python.

In some other programming languages null is often defined to be 0, however in Python None is not defined to be 0 or any other value. It is simply – None.


None in practice

How to remove none values from a list

Here is an example of a basic task - removing none values from an array.

#remove none values from a list my_list = [0, 3, None, 10, 0, None, 25] new_list = [x for x in my_list if x is not None] print(new_list)