Alex Rivera | Logout

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

Asked 2010-10-10T16:33:35.450
57

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.

Edit
Report

2 Answers

71

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
answered 2010-10-10T16:44:23.223
4
if x:
    # Evaluates for any defined non-False value of x
if not x:
    # Evaluates for any defined False value of x
if x is None:
    # Evaluates for any instances of None

None is its own type, which happens to be False. "if not x" evaluates if x = None, only because None is False.

There aren't any subtle differences that I know of but there are exact methods to test for use for positivity/negativity in exact situations. Mixing them can work in some situations, but can lead to problems if they're not understood.

if x is True:
    # Use for checking for literal instances of True
if x is False:
    # Use for checking for literal instances of False
if x is None:
    # Use for checking for literal instances of None
if x:
    # Use for checking for non-negative values
if not x:
    # Use for checking for negative values
    # 0, "", None, False, [], (), {} are negative, all others are True
answered 2010-10-14T20:58:49.400

Your Answer