Compare to None

How do we check if something is None?

With the beauty of the Python language - the code that you would write is literally the same as the above question:

if something is None:

It reminds me of this joke:

- How do you turn pseudocode into Python?
- You add .py at the end of the file.

There is another way in which we could make this comparison:

if something == None:

However, it doesn't make sense to use the second variant. None is a singleton object - there can't be two different None objects in your code. Each time you assign None to a variable, you reference the same None:

>>> a = None
>>> b = None
>>> c = None
>>> a is b is c
True

To compare the identity, you should use is, rather than ==, as I explained in the Checking for True or False article. It's clearer and faster:

$ python -m timeit -s "a = 1" "a is None"
50000000 loops, best of 5: 8.2 nsec per loop

$ python -m timeit -s "a = 1" "a == None"
20000000 loops, best of 5: 13 nsec per loop

As you can see, == is 60% slower than is (13 / 8.2 ≈ 1.59).

Similar posts

Inlining Functions

Running one big blob of code is often faster than splitting your code into well-separated functions. But there are other ways you can improve the speed of your code without sacrificing its readability.

You Don't Have to Migrate to Python 3

Python 3 is great! But not every Python 2 project has to be migrated. There are different ways how you can prepare for the upcoming Python 2 End of Life.

dict() vs. {}

Is using {} faster than dict()? If yes, then why? And when would you use one version over the other?


Previous:
WTF Excel?!