Python’s NoneType type

Tue Nguyen
2 min readApr 15, 2022

--

NoneType is used to represent the state of being undefined/unknown. Python uses the keyword None to represent this special value.

To create a variable of NoneType, simply assign None to it, for example

x = Nonetype(x)NoneType

When you evaluate None on a code cell of Jupyter Lab, you will not see anything printed out.

x

To display None you have to explicitly print it out using print().

print(x)None

You can also create a NoneType variable by assign to it an expression that produces None, for example

x = print("Hello")Hello

Many misunderstand that x will assume the value "Hello" after the above assignment. It's not true.

"Hello" is what print prints out, it's not what print returns. You will learn more about function later. For now, just accept that print prints out "Hello", but after the printing is done, it returns something else to the place where it is called. This returned value is None.

Let’s confirm it.

type(x)NoneType

When use NoneType?

NoneType is normally used as a return option of a function to indicate that the function already did what you asked, but it couldn't find anything that makes sense.

Suppose we have a string s as follows.

s = "This is a dog"

Now, suppose we want to check if some other string is contained in s. We can use re.search() function of module re.

First, we need to import module re to use its search function.

import re

Now, check if "cat" is in s.

find = re.search("cat", s)

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

As you can see, the result is None because there is no "cat" in s. Now, try to search for "dog".

find = re.search("dog", s)

print(find)
print(type(find))
<re.Match object; span=(10, 13), match='dog'>
<class 're.Match'>

As you can see, this time, re.search() found something, and it did not return None. Instead, it returned a re.Match object that contain the relevant information about the search result.

Operations on NoneType

There is not much we can do with NoneType because it is so simple. The most commonly used operation is to check if a variable is actually None. To do this, we perform a comparison using is.

x = None# Check if x is None
x is None
True# Check if x is not None
x is not None
False

Remarks:

  1. We can also compare using ==, but it is not recommended. For a detailed explanation, read here.
  2. For now, you might not appreciate NoneType much. But you will after gaining an adequate knowledge about Python.

Navigation

Previous: Python’s typing system
Next: Python’s truth values (bool) type

--

--

Tue Nguyen

Former data scientist. MSc student in quantitative economics. Love sharing data science stuff.