Null in Python: What is it and Why is it useful?

There’s no null in Python; instead, there’s None. The null is called None in Python, a special object representing the absence of a value. The null object is the singleton None. “Null” is a unique value in Python that demonstrates that a variable doesn’t point to anything.

Many would argue that the word “null” is somewhat esoteric, but Null is not precisely the friendliest word to programming novices.

The “None” refers precisely to the intended functionality – it is nothing and has no behavior. In Python, None is the object and first-class citizen!

Many programming languages use Null to represent a pointer that doesn’t point to anything. It’s a placeholder when a variable is empty or to mark default parameters you haven’t supplied. The Null is often defined as 0 in those languages, but the Null in Python differs.

The difference between Null and None in Python

There is no null in Python, like in other programming languages. Instead, there is None. The Null is often defined as 0 in different programming languages, but the Null in Python differs.

Python uses a None differently because it defines null objects and variables.

Why does null matter in Python?

Null matters in Python because it represents the absence of value. Null can be used as a placeholder for an unknown or uninitialized value. If a function does not return any value, then it returns None.

The Null deserves a particular purpose in Python, and it does not mean the value 0. The None or Null is a first-class citizen.

None in Python

None in Python is used to describe a null or no value. None means Falsy. value or an empty string. None is data of its own (NoneType), and only None can be None.

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.

In the output, you can see that the parameter key has a None value. That means the key parameter is required, but we have not provided it; that is why the default parameter is None.

How to Set a Value to None?

To set a value to None in Python, 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.

Proof that None is an Object

None is the singleton, and the NoneType class only gives you the same single instance of None. There’s only one None in our Python program.

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

  1. None is not the same as False.
  2. None is not an empty string.
  3. None is not 0.
  4. Comparing None to anything will always return False except None itself.

Declaring None in Python

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

Let’s assign the None value to a variable in Python and print the variable in the console.

data = None
print(None)

Output

None

If we don’t define a variable and direct 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.

Return null in Python

To return a null in Python, use the None keyword. There is no such term as “return null” in Python. 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

Python is not null

To check if a variable is null in Python, use the “is not” operator. Python “is” and “is not” operators are comparison operators that compare the identity of two objects. For example, python “is operator” is an identity test. It checks whether the right-hand and left-hand sides are the same object.

var = "Stranger Things 4 Vecna"

if var is not None:
  print('Var is not null')

Output

Var is not null

You can see that var is not null or None. That’s why if condition holds True and print the statement.

Using None as part of a comparison

There’s no null in Python. Instead, there’s None. As stated, the most accurate way to test that something has been given None as a value is to use the identity operator, which tests that two variables refer to the same object.

In Python, 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, it is probably more correct to use it rather than “==”. Not sure if there is even a speed difference.

When checking None values, an essential rule of thumb is to keep in mind.

  1. Do use identity operators is and is not.
  2. Do not use the equality operators == and !=.

The difference between == and Python is Operator.

The difference between the == and is operator in Python 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 indeed 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

In other programming languages, Null is just a synonym for 0, but Null in Python 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 in Python

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.

  1. new_item: This item will be added to the list if we pass when calling the function.
  2. 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(). 

  1. new_item = DoAppendNone
  2. 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.

That means, inside the function, we have checked if the initial_list is None, but it is None as we have a list of items in data, so that condition will be False.

The second condition is that new_element should not be DoAppendNone, but it is. So that condition will be False also. So, no new element will be added to the list.

Finally, the provided data list will be returned as an output.

Now, what if None is a valid input object? For instance, what if list_function() could either insert an item to the list or not, and None was a valid element to append?

In this case, you can define the class specifically for use as default while being distinct from None.

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]

Here, the class DoAppendNone serves as 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 in Python.

The None is the inbuilt 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.

Checking if the value is None

Why do this

value is None

rather than

value==None

The first is equivalent to:

id(value)==id(None)

Whereas the expression value==None is applied like this,

value.__eq(None)__

if the value is None, then you’ll get what you expected.

>>> nothing = function_that_does_nothing()
>>> nothing.__eq__(None)
True

This is because none has a distinctive status in the Python language. It’s a preferred baseline value because many algorithms treat it as exceptional.

In such scenarios, it can be used as the flag to signal that the condition requires special handling, such as setting the default value.

None in Tracebacks

When NoneType appears in your traceback, it means that something you didn’t expect to be None was None, and you tried to use it in a way that you can’t use None. Almost always, it’s because you’re trying to call a method on it.

data = [1, 2, 3, 4, 5]

data.append(6)
print(data)

data = None
data.append(11)
print(data)

Output

[1, 2, 3, 4, 5, 6]
Traceback (most recent call last):
  File "app.py", line 7, in <module>
    data.append(11)
AttributeError: 'NoneType' object has no attribute 'append'

When we define a list with some initial values, it can call the list.append() function to add an element to the list, but when we define a list to None, that means now that list is not a traditional Python list, that list is now None, and the None object does not have an append() method to work with that is why it throws an AttributeError.

When you see a traceback like the above in your code, look for the first attribute that raised the error. Here, it is an append() method. Next, you’ll see the object you tried to call from there. Finally, figure out how that object became None and take the necessary steps to fix your code.

Conclusion

None in Python is an immutable keyword and powerful tool like True or False. None can be tested using in or not in operators. In tracebacks, None can help find the exact problem, and we can fix it by solving the Null issue.

There can be only one None in any Python program, and even if you create an instance of the NoneType class, there can only be one None.

That’s it for this tutorial.

Related posts

Python check nan

Python isnan

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.