There’s no null in Python; instead, there’s None. The Null is called None, a special object representing the absence of a value. None is a unique value demonstrating that a variable doesn’t point to anything.
Many would argue that “null” is somewhat esoteric, but Null is not precisely the friendliest word to programming novices.
Declaring None
We can assign a None object to any variable at the time of declaration.
Python variables come to life through an assignment operator, which helps us give a particular value to the variable.
Some programming languages don’t have to have an initial value assigned to them. For example, the initial value for some variables might be null.
Visual representation
Let’s assign the None value to a variable and print the variable in the console.
data = None
print(None)
Output
None
If we don’t define a variable and directly print its value, we will get NameError.
print(data)
Output
Traceback (most recent call last):
File "app.py", line 2, in <module>
print(data)
NameError: name 'data' is not defined
All variables in Python come into life through the assignment operator. A variable can only start life as Null if you assign None. If you don’t define a variable and directly try to print in the console, you will get NameError.
Why does None matter?
None matters because it represents the absence of value.
None can be used as a placeholder for an unknown or uninitialized value.
If a function does not return any value, then it returns None. It deserves a particular purpose, and it does not mean the value 0. The None or Null is a first-class citizen.
If you define a function with a return statement or no value, it returns None.
def python_none():
pass
print(python_none())
Output
None
When you call the python_none() function, it returns None because there is no return statement. Instead, there is only a pass statement.
None has no output value, but printing shows None to the Python console, explicitly forcing us to print the output.
None indicates missing or default parameters. For example, None appears twice in the docs for the list.sort() function.
print(help(list.sort))
Output
sort(self, /, *, key=None, reverse=False)
Sort the list in ascending order and return None.
The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
order of two equal elements is maintained).
If a key function is given, apply it once to each list item and sort them,
ascending or descending, according to their function values.
The reverse flag can be set to sort in descending order.
Setting a Value to None
To set a value to None, assign a None object to a variable that becomes None.
data = None
In the above code, you can see that we set a data variable to None using the assignment operator.
None is the singleton, and the NoneType class only gives you the same instance of None.
NoneObj = type(None)()
print(NoneObj)
# Check if NoneObj is instance of NoneType class
print(NoneObj is None)
It gives the following output.
None
True
Even though you try to create the new instance, you still get the existing None.
Interesting Facts about None
- None is not the same as False.
- None is not an empty string.
- None is not 0.
- Comparing None to anything will always return False except None itself.
Returning None
To return a null, use the None keyword. There is no such term as “return null”. Instead, every function returns some value.
Python treats it as returning None if no explicit return statement is used.
def FuncNull(data):
print(data)
return None
print(FuncNull("Function Called"))
Output
Function Called
None
is not null
To check if a variable is null, use the “is not” operator.
Visual representation
The “is” and “is not” operators are comparison operators that compare the identity of two objects.
For example, “is operator” is an identity test. It checks whether the right-hand and left-hand sides are the same object.
str = "Stranger Things 4 Vecna"
if str is not None:
print('String is not null')
Output
Var is not null
You can see that var is not null or None. That’s why if the condition holds print the statement.
Using None as part of a comparison
To represent an absence of the value, you can use a None value (types.NoneType.None) for objects and “”(or len() == 0) for strings.
Regarding the difference between “==” and “is” testing for object identity using “==” should be sufficient.
However, since the operation “is” is defined as an object identity operation, using it rather than “==” is probably more correct. I am not sure if there is even a speed difference.
When checking None values, an essential rule of thumb is to keep it in mind.
- Do use identity operators is and is not.
- Do not use the equality operators == and !=.
The difference between == and is Operator.
The difference between the == and is operator is that the == operator compares the values of both operands and checks for value equality. At the same time, is operator checks whether both operands refer to the same object.
See the following code.
eleven = None
print(eleven is None)
See the following output.
True
Now, see the following code.
def python_none():
pass
data = python_none()
print(data == None)
print(data is None)
Output
True
True
This code returns None, and we check that the data is None.
But, The equality operators can be fooled when you compare user-defined objects that override them.
class isAndDoubleEqual:
def __eq__(self, other):
return True
res = isAndDoubleEqual()
print(res == None)
print(res is None)
Output
True
False
The equality operator == returns the incorrect answer.
The identity “is operator” returns the correct answer because it can’t be fooled because you can’t override it.
Checking type of None
None is just a synonym for 0 in other programming languages, but it is an object.
Check the type of None using the type() method.
print(type(None))
Output
<class 'NoneType'>
This shows that None is the object, and its data type is NoneType.
None by itself is built into the language as the Null in Python. However, you can check it out by printing the dir(__builtins__).
print(dir(__builtins__))
It will print the following built-in items.
['ArithmeticError',..., None,....., zip
Using None as a Value
We can pass None as a function parameter in Python and add it to the list. First, we will define a class, and we don’t define its body. Then, we create a function called list_function(), which takes two parameters.
- new_item: This item will be added to the list if we pass when calling the function.
- initial_list: As a default parameter, the list should be None, but if we pass any argument explicitly, it will return the initial list.
class DoAppendNone:
pass
def list_function(new_item=DoAppendNone, initial_list=None):
if initial_list is None:
initial_list = []
if new_item is not DoAppendNone:
initial_list.append(new_item)
return initial_list
data = [1, 2, 3, 4, 5]
print(list_function(initial_list=data))
Output
[1, 2, 3, 4, 5]
We have passed two parameters with the default value of the list_function().
- new_item = DoAppendNone
- initial_list = None
In the code, we have passed the initial_list as data because we have a data list that has five elements.
So, when calling the function, our initial_list = data.
So, let’s write a program that inserts a None value as an element to the list.
class DoAppendNone:
pass
def list_function(new_item=DoAppendNone, initial_list=None):
if initial_list is None:
initial_list = []
if new_item is not DoAppendNone:
initial_list.append(new_item)
return initial_list
data = [1, 2, 3, 4, 5]
print(list_function(None, data))
Output
[1, 2, 3, 4, 5, None]
The class DoAppendNone is a signal not to append, so you don’t want None. That frees us to insert None whenever we want.
Checking None using if…else condition.
We can write the following code to check if the value is None.
value = None
if value is None:
print('The value is null')
else:
print('The value is not null')
In the above example, we have defined the variable called value and assigned the None value.
Then, we used the if…else condition to check the None value, and if it does, return the print statement with “The value is null.”
We can use the following code to check if the name exists.
try: val except NameError: pass # val does not exist at all
There can be only one None
The None is a built-in constant as soon as you start Python, whether in a module, class, or function. The NonType, by contrast, is not; you’d need to get a reference to it first by querying None for its class.
>>> NoneType NameError: name 'NoneType' is not defined >>> type(None) NoneType
None can be overwritten.
Before Python 2.4, it was possible to reassign None, but not anymore. Not even as the class attribute or in the confines of a function.
Related posts
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.