Difference between null and none in Python

Introduction

First, keep in mind that null is not part of the Python programming language syntax, though you can find it in other programming languages (ex. Java, JavaScript). In Python syntax, it is None. So what is None ? Do we really need it ? how is it used ?

let us discuss that…

None in plain English

None has no special meaning other than what the Python syntax has given it. It is a convenient way to indicate that a particular variable has no object value assigned. For example, you may declare a variable and assign it the None value before you instantiate a given class. Another example is to call a function that does not return any value. In this case, None is returned by default. Take a look…

That is what None means in plain English but what does it mean technically?

Technical meaning of None

Technically speaking, None is an instance of the NoneType object type (class if you like). It is a singleton (there is only one instance during the lifetime of the program). It is read only, you can not modify the attributes of that object otherwise you get syntax errors. Take a look…

As we indicated earlier, None is used to refer to the lack of value so during the course of program execution, it is a common task to check if a given variable is None. How can we do that ? Take a look at the following code snippets…

Comparison code snippets

In Python, there are various ways to perform comaprison. We can test for equality or check the identity of objects. The following code snippet demonstrates equality and identity checks….

Can we use boolean logic to test for None ? Yes we can ! None behaves in a similar way to empty collections, when casted to a boolean, it returns a False. Here is an example…

The output should be something like…

Finally, which method is best to check for None ? I leave that up to the reader but I personally think it is recommended to use identity check using the (is) operator because None in Python is a special purpose object that can be uniquely identified.

Summary

  • None in Python is a convenient way to indicate that a particular variable has no object value assigned
  • Technically speaking, None is the sole instance of the NoneType object type
  • To test for None, we can use equality, identify or boolean checks

That is it for today. Thanks for visiting. Please comment below if you have questions.

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *