Difference between "if x" and "if x is not None"

It appears that "if x" is almost like short-hand for the longer "if x is not None" syntax. Are they functionally identical or are there cases where for a given value of x the two would evaluate differently?

I would assume the behavior should also be identical across Python implementations - but if there are subtle differences it would be great to know.


Solution 1:

In the following cases:

test = False 
test = "" 
test = 0
test = 0.0 
test = []
test = () 
test = {} 
test = set()

the if test will differ:

if test: #False

if test is not None: #True 

This is the case because is tests for identity, meaning

test is not None

is equivalent to

id(test) == id(None) #False

therefore

(test is not None) is (id(test) != id(None)) #True

Solution 2:

The former tests trueness, whereas the latter tests for identity with None. Lots of values are false, such as False, 0, '', and None, but only None is None.

Solution 3:

x = 0
if x: ...  # False
if x is not None: ... # True