Python: if not val, vs if val is None

No. If you want to run code when the value is false but isn't None, this would fail horribly.

Use is None if you're checking for identity with the None object. Use not value if you just want the value to be False.


Use a comparison to None if that's what you want. Use "if not value" if you just want to check if the value is considered false (empty list, none, false).

I find "if not value" to be cleaner looking and Pythonic.

Also, be careful with lists. You should not use is when comparing for an empty list. If you know you're getting a list, use if <list> to check if it has any contents (or len()). Try typing this into the interpreter:

>>> a = []
>>> a is []
False

This is because the temporary list you just made has a different address in memory than the one stored at 'a'. You don't see this with None, False, or True because these are all values that are singletons (they all refer to the same section of memory) so using the 'is' keyword works.

You'll also find that CPython interns strings so the following works.

>>> 'a' is 'a'
True

You should not rely on this. It is an implementation detail and this is not specified to work with every version of Python.