None Keyword in Python

The None keyword is an object that defines a null value. It is an object of the class NoneType and is not the same as zero, False, or an empty string.

print(type(None))

Output

<class 'NoneType'>

When we assign a variable to None, we reset the value of the variable to its original state. None is a singleton i.e all the variables assigned to None value points to the same object.

Consider two variables var_1 and var_2 assigned to the value None. The address of both the variables is the same. This represents both the variables point to the same object.

var_1 = None
var_2 = None
print("ID of var_1: ", id(var_1))
print("ID of var_2: ", id(var_2))

Output

ID of var_1:  140731870100696
ID of var_2:  140731870100696

None Vs Null

In many programming languages like C, C++ Java, etc there is a Null keyword. But in python instead of a Null value, we have a None keyword.

The Null keyword in other languages is used to represent a pointer that doesn't point to anything, to denote a variable that is empty and is often defined as 0. The None keyword in python is not defined as 0 or any other value. Python uses the None keyword to define a null value or an object.

Taking None as input value in python

Consider the following example, a input() function takes the user input. If the user enters a value in the console, that particular value is assigned to the variable var_a. If nothing is entered then input function returns an empty string. An empty string is evaluated to False in python. Hence, the or operator returns None object as a value to the var_a.

var_a = input("Enter a value:") or None
print("var_a: ", var_a)
print(type(var_a))

Output

Enter a value:
var_a:  None
<class 'NoneType'>

assert a value is None

assertIsNone() is a inbuilt function in unittest library. The assertIsNone() function takes two parameters a test variable and a string message. The function checks if the test variable is equal to None. If the test variable is not equal to None the string message is displayed.

import unittest
class Testfunc(unittest.TestCase):
    def test_negative(self):
        test_none = None
        test_var = "ABC"
        self.assertIsNone(test_none, "test_none is none.")
        self.assertIsNone(test_var, "test_var is not none.")
  
if __name__ == '__main__':
    unittest.main()

Output

F
======================================================================
FAIL: test_negative (__main__.Testfunc)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "E:/Internship files/none.py", line 131, in test_negative
    self.assertIsNone(test_var, "test_var is not none.")
AssertionError: 'ABC' is not None : test_var is not none.

----------------------------------------------------------------------
Ran 1 test in 0.006s

FAILED (failures=1)

Using None with If statement

None is a falsy value. Values that are evaluated to False are considered as falsy values. The following example illustrates the use of None keyword with If statement.

var_a = None
if var_a:
    print("var_a is not None")
else:
    print("var_a is None")

Output

var_a is None

Check if something is None or not in Python

We can check if a variable is assigned with a None value or not using "is" operator, == operator, type() or isinstance() method.

Checking if something is None using "is" operator

The "is" operator compares the variable with the None keyword and returns a boolean value.

my_var = None
if my_var is None:
    print("my_var is of NoneType")
else:
    print("my_var is not of NoneType")

Output

my_var is of NoneType

Checking if something is None using == operator

Consider the following example, the double equal to (==) operator compares if a variable is assigned to a None type object and returns a boolean value.

my_var = None
if my_var == None:
    print("my_var is of NoneType")
else:
    print("my_var is not of NoneType")

Output

my_var is of NoneType

Checking if something is None using type() method

The type() function returns the type of the object. In the following example, we check if the type of the variable is equal to the type of None object. If the condition is True, then the variable is equal to None.

my_var = None
if type(my_var) == type(None):
    print("my_var is of NoneType")
else:
    print("my_var is not of NoneType")  

Output

my_var is of NoneType

Checking if something is None using isinstance() method

The isinstance() method checks if a specified object is of a specified type and returns a boolean value. The syntax for the isinstance() method is given below.

isinstance(object, type)

Consider the following example, the isinstance() method checks if variable my_var is an instance of NoneType and returns the boolean value.

my_var = None
if isinstance(my_var, type(None)):
    print("my_var is of NoneType")
else:
    print("my_var is not of NoneType")

Output

my_var is of NoneType

Can we store None in a list, set, and dictionary?

We can store None value in sequences such as list, tuple, set, or dictionary.

my_list = [1, 2, None]
print("my_list: ", my_list)
my_set = {1, None, 5}
print("my_set: ", my_set)
my_dict = {'A': None, 'B': None}
print("my_dict: ", my_dict)

Output

my_list:  [1, 2, None]
my_set:  {1, 5, None}
my_dict:  {'A': None, 'B': None}

Appending None in a list, set, dictionary

A None value can be added to the list by using the append() method, to a set by using add() method, to a dictionary by using a new index key.

my_list = [1, 2]
my_list.append(None)
print("my_list: ", my_list)

my_set = {1,5}
my_set.add(None)
print("my_set: ", my_set)

my_dict = {1: "red"}
my_dict[2] = None
print("my_dict: ", my_dict)

Output

my_list:  [1, 2, None]
my_set:  {None, 1, 5}
my_dict:  {1: 'red', 2: None}

Checking None value in a list, set, and dictionary

We can use the "in" operator or for loop to check the existence of the None value in the list, set, or dictionary.

Checking existence of None value in a list, set, and dictionary using "in" operator

In python, the "in" operator checks the presence of a value in a sequence(string, list, tuple, set, dictionary). It returns a boolean value 'True' if the item is found in the sequence else it returns False.

my_list = [1, 2, None]
print("my_list: ", my_list)
if None in my_list:
    print("None value is present in my_list")

my_set = {1, None, 5}
print("my_set: ", my_set)
if None in my_set:
    print("None value is present in my_set")

my_dict = {'A': None, 'B': "red"}
print("my_dict: ", my_dict)
if None in my_dict.values():
     print("None value is present in my_dict")   

Output

my_list:  [1, 2, None]
None value is present in my_list
my_set:  {1, 5, None}
None value is present in my_set
my_set:  {'A': None, 'B': 'red'}
None value is present in my_dict
Checking existence of None value in a list, set, and dictionary using for loop

Consider the following example, a user-defined function Check_None checks the existence of None value in a sequence. A for loop iterates over the sequences(list, set, dictionary). In each iteration, the program checks if the item is equal to the None value.

If the condition is true if block is executed and output is printed. Otherwise, the function returns the statement as Not Found.

def Check_None(seq):
   print("sequence received: ", seq)
   for item in seq:
       if item == None:
           return "None Value Found"
   return "Not Found"

my_list = [1, 2, None]
print("my_list: ", Check_None(my_list))

my_set = {1, None, 5}
print("my_set: ", Check_None(my_set))

my_dict = {'A': None, 'B': "red"}
print("my_dict: ", Check_None(my_dict.values()))

Output

sequence received:  [1, 2, None]
my_list:  None Value Found
sequence received:  {1, 5, None}
my_set:  None Value Found
sequence received:  dict_values([None, 'red'])
my_dict:  None Value Found

Return None in Python

We can return the None value in python by using the pass statement or by writing the return None statement explicitly.

Returning None using the "pass" statement

In python, a pass is a null statement. The pass statement doesn't do anything. The pass statement is useful when we don't have any implementation for a function, loops, etc but we want to execute it in near future.

Example 1:

def my_func():
    pass
print(type(my_func()))

Output

<class 'NoneType'>

Example 2: If a string is not a numeric string, let's returns None.

def my_func(string):
    if string.isnumeric():
        return("Numeric string")
    else:
        pass
my_str = '12Hg'
print("my_str: ", my_str)
print(my_func(my_str))

Output

my_str:  12Hg
None

Returning None using the return None statement explicitly

We can return None by using the return None statement explicitly.

Example 1:

def my_func():
    return None
print(my_func())

Output

None

Example 2: If a string is not a numeric string the function returns None using the return None statement.

def my_func(string):
    if string.isnumeric():
        return("Numeric string")
    else:
        return None
my_str = '12Hg'
print("my_str: ", my_str)
print(my_func(my_str))

Output

my_str:  12Hg
None

Returning None using an empty return statement

An empty return statement also returns a None value. Consider, the following example, where my_func() returns None if the given string is not a numeric string.

def my_func(string):
    if string.isnumeric():
        return("Numeric string")
    else:
        return 
my_str = '12Hg'
print("my_str: ", my_str)
print(my_func(my_str))

Output

my_str:  12Hg
None

Returning None without using a return statement

A function without any return statement returns a None value. Consider the following example, where the function my_func() returns a None value if a string is not a numeric string.

def my_func(string):
    if string.isnumeric():
        return("Numeric string")
my_str = '12Hg'
print("my_str: ", my_str)
print(my_func(my_str))

Output

my_str:  12Hg
None

Avoid returning None in python

A function returns None if no return statement is specified. To avoid returning None we can return some other default value or a statement if a condition is not met.

Consider the following example, where the function my_func() returns a default statement 'Not numeric string' if a string is not a numeric string.

def my_func(string):
    if string.isnumeric():
        return("Numeric string")
    return "Not numeric string"
my_str = '12Hg'
print("my_str: ", my_str)
print(my_func(my_str))

Output

my_str:  12Hg
Not numeric string

Comparing None with an empty string, list, tuple set, and dictionary

An empty string or empty sequences(list, tuple, set, or dictionary) are not equal to the None value. Comparison of an empty string and sequences using == operator returns False.

string_1 = ""
print("string_1 == None: ", string_1 == None)

list_1 = []
print("list_1 == None: ", list_1 == None)

tuple_1 = tuple()
print("tuple_1 == None: ", tuple_1 == None)

set_1 = {}
print("tuple_1 == None: ", set_1 == None)

dict_1 = dict()
print("dict_1 == None: ", dict_1 == None)

The above code returns the output as

string_1 == None:  False
list_1 == None:  False
tuple_1 == None:  False
tuple_1 == None:  False
dict_1 == None:  False

Comparing two None value

We can compare None with None using the == operator.

print("None == None: ", None == None)

Output

None == None:  True

Comparing None with False

The None keyword is not the same as False. Comparing None with False using == operator returns False. But, if we evaluate None using if block then, None results in falsy value.

print("None == False: ", None == False)

Output

None == False:  False

TypeError exception

The python program raises a TypeError exception if we try to iterate over a None value, or convert a None object to numeric data type using int(), float, etc.

Example 1: Iterating a None variable

var = None
for i in var:
    print(i)

Output

 for i in var:
TypeError: 'NoneType' object is not iterable

Example 2: Typecasting the None value to int data type

val_1 = int(None)
print("val_1: ", val_1)

Output

 val_1 = int(None)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
ValueError exception

The python program raises a ValueError exception if the user provides None as input to the variable instead of integer type input.

val_1 = int(input())
print(val_1)

Output

  val_1 = int(input())
ValueError: invalid literal for int() with base 10: 'None'
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions