Null object in Python
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:
Or, you can define a function that doesn't return anything like this:
def my_function():
print("Hello World!")
return_value = my_function()
print(return_value) # prints None
It is also often used as a placeholder for function arguments which are optional and the default value is not provided .
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.
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.