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.

0

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.