W3docs

Null object in Python

In Python, the "null" object is called None.

In Python, the "null" object is called None. It is a special object that represents the absence of a value or a null value. It is an instance of the NoneType class and only has one value, which is None.

You can use the None object to represent the absence of a value in a variable or a function that doesn't return any value. For example, you can initialize a variable with no value like this:

Initialize a variable with no value in Python

x = None
print('x is defined as: ', x)

Or, you can define a function that doesn't return anything like this:

Define a function that doesn't return anything to have a None value in Python

def my_function():
    print("Hello World!")

return_value = my_function()
print(return_value)  # prints None

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

It is also often used as a placeholder for function arguments which are optional and the default value is not provided .

Define functions with default None placeholders in Python

def example(arg = None):
    if arg is None:
        print("arg not provided")
    else:
        print("arg provided: ",arg)

example() # arg not provided
example("Provided arg") # arg provided: Provided arg

It can also be useful in certain type of iteration and traversal when there is no data in the container, to check if iteration should end or not.

Use a None value in Python to check if iteration should end or not

while node is not None:
    print(node.value)
    node = node.next

Note that None is a singleton, which means that all variables that are assigned None are actually references to the same object in memory. You can check that by using the is keyword.

Check if a value is a None in Python

x = None
y = None

print(x is y) #True