3

I have:

x = None

Many references I have found so far do the "null" check in the following fashion:

if x is None:
    ...

(for example, this question).

Whereas throughout my code I have:

if not x:
    ...

What I am doing currently works as predicted (returns true), but I'd like to know if there are any use cases where it is optimal to perform the check the way it is done in the first example.

Apologies if this is very obvious or if the question has been asked before - I couldn't find the answer to this specific Q on the site.

Community
  • 1
  • 1
Wilson Canda
  • 434
  • 5
  • 19

1 Answers1

5

not x will also return True for everything that evaluates to False in a boolean context. Some examples:

>>> x = ()
>>> not x
True
>>> x = []
>>> not x
True
>>> x = ''
>>> not x
True    
>>> x = 0
>>> not x
True    
>>> x is None
False

So if your code should act differently when x is None as opposed to x being an empty list, tuple, string, the number zero, ... then use x == None or x is None instead of not x.

timgeb
  • 76,762
  • 20
  • 123
  • 145