Null in Python

In Python, there is no such value as null.

Instead, Python has None that represents null.

You can use an if-statement to check if a value is None in Python:

For example:

name = None

if name is None:
    print("None found")
else:
    print(name)

Output:

None found

Today, you are going to learn everything about the None object in Python.

History of Null Values in Programming

In programming, a null value means a parameter does not have a value (at least yet).

It is like a placeholder for empty variables.

Null in programming

To get a better idea about null values, let’s use a real-life example.

Let’s say you have a variable n that represents how much money you have.

  • If n == $100, you have 100 dollars
  • If n == $0, you have no money
  • If n == null, you haven’t checked if you have money or not. Thus in this example, null represents the case where you don’t know how much money you have.

Many programming languages represent this absence of value as null.

However, in Python, None is used instead.

None in Python

In Python, a function automatically returns None when there is no return statement in a function.

For example, let’s create a function that does not return anything.

The simplest way to do this is by using the pass statement:

def test():
    pass

Let’s call this function and print the returning value:

print(test())

Output:

None

As you can see, the function returns None.

Let’s see another example.

Python’s built-in print() function does not return anything. This is a fact that you have probably not thought about before.

Because the print() function does not return a value, it returns None.

To see this, you can print the result of a print() call:

print(print("Example"))

Output:

None

Instead of printing “Example”, None is printed is because print(“Example”) itself returns None.

Facts About None Object in Python

Here are some facts about the None object:

  • None is not the same as False.
  • An empty string is not the same as None.
  • None is also not a zero.
  • Any comparison with None returns False, except for comparing None with itself.

Here I am using Python REPL to verify these:

>>> None is False
False

>>> None == ""
False

>>> None == 0
False

>>> None == "None"
False

>>> None == None
True

How to Use and Deal with None in Python

In Python, None represents the absence of a value.

You commonly use None to:

  • Make comparisons to see if a value is None or not.
  • Provide an empty default argument value for a function.

You also commonly see NoneType in the traceback error messages.

This is because you have an unexpected None value somewhere in the code and you try to use it.

None in Comparisons

None is commonly seen when making comparisons in Python.

To compare an object with None, use the identity operator is (and is not).

For example:

number = None
name = "Alice"

number is None    # Returns True
name is not None  # Returns True

Generally, to check if a value is None in Python, you can use the if…else statement.

For instance, let’s check if a name variable is None:

name = None

if name is None:
    print("None found")
else:
    print(name)

Output:

None found

None as a Default Parameter

A None can be given as a default parameter to a function.

This means if you call the function without specifying the parameter None is used as a fallback.

For example, let’s create a function that greets a person only if a name is given as an argument:

def greet(name=None):
    if name is not None:
        print(f"Hello, {name}!")


greet()         # Prints nothing
greet("Alice")  # Prints "Hello, Alice!"

This function works such that:

  • If a name is not specified, it defaults to None. As a result, the function does nothing.
  • If a name is specified, the function greets the person with that name.

None as a default parameter is a common way to use None in Python.

If you take a look at the official documentation of Python, you see None used this way in the list.sort() method for example.

The key parameter is None by default.

Debugging a NoneType in a Traceback

When writing Python code, you commonly stumble across an error like this one:

AttributeError: 'NoneType' object has no attribute 'SOMETHING'

If you see this or any other error with the word NoneType it means you are using None in a way it cannot be used.

In other words, something that is not supposed to be None is accidentally None.

For instance, let’s create a function that returns a list of names and call it:

def give_names():
    ["Alice", "Bob", "Charlie"]

names = give_names()

for name in names:
    print(name)

Instead of printing the names, an error occurs:

TypeError: 'NoneType' object is not iterable

This happens because we forgot to return the names in the give_names() function.

As you learned earlier, when a function does not use the return keyword, None is returned automatically.

As a result of this little mistake, we try to iterate over the None object.

In this case, the fix is simple—return the names from the function:

def give_names():
    return ["Alice", "Bob", "Charlie"]

names = give_names()

for name in names:
    print(name)

Now the function works as we expected:

Alice
Bob
Charlie

This serves as one example of how to track down an error with NoneType.

Whenever you see this error, something similar is happening.

None Object Under the Hood in Python

In many popular programming languages, null is just a 0 under the hood.

In Python, this is not true.

Just like everything else in Python, None is an object.

This is easy to verify by checking the type of None in Python REPL:

>>> type(None)
<class 'NoneType'>

The type of None is NoneType. This is because NoneType is the base class that implements the None object.

In Python, None is a singleton object.

This means there is only one None in Python at your disposal.

No matter where you see None, it is always the same None none object.

Let’s verify this by creating multiple variables with None as their value and checking their id:

n1 = None
n2 = None
n3 = None

print(id(n1))
print(id(n2))
print(id(n3))

Output:

4398896592
4398896592
4398896592

All the variables return the same id.

This verifies that there is only one None.

None object in Python

In other words, the variables n1, n2, and n3 are also the same object because they point to the same memory address.

None Is a True Constant in Python

Let’s go further into the details of None.

None is an object in Python. But it is a special object that you cannot modify.

Let’s see what happens if you try to modify the None object in Python:

>>> None = 50
SyntaxError: cannot assign to None

Also, you cannot add properties to the None object:

>>> None.length = 50
AttributeError: 'NoneType' object has no attribute 'length'

Modifying the None object is not possible, because it is a true constant in Python.

As discussed earlier, this can cause errors and bugs in your code. Luckily, the error message is clear enough to tell you what is going on.

Subclassing the underlying type NoneType of None is not possible.

For instance:

class CustomNone(type(None)):
    pass

Result:

TypeError: type 'NoneType' is not an acceptable base type

Conclusion

Python null is called None.

None is a special object that represents the absence of a value.

A function that does not return a value automatically returns None.

Comparisons with None evaluate True only when comparing None with itself.

Any other comparisons yield False.

Thanks for reading. I hope you find it useful.

Happy coding!

Further Reading

Python Interview Questions and Answers

Useful Advanced Features of Python

Leave a Comment

Your email address will not be published.