5

Consider this list:

list = [1,2,3,4,5]

I want to check if the number 9 is not present in this list. There are 2 ways to do this.

Method 1: This method works!

if not 9 in list: print "9 is not present in list"

Method 2: This method does not work.

if 9 in list == False: print "9 is not present in list"

Can someone please explain why method 2 does not work?

Raghav Mujumdar
  • 513
  • 1
  • 5
  • 10
  • 2
    see http://stackoverflow.com/questions/7479808/python-operator-precedence-of-in-and-comparision – grc Mar 11 '13 at 10:47

2 Answers2

19

This is due to comparison operator chaining. From the documentation:

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

You are assuming that the 9 in list == False expression is executed as (9 in list) == False but that is not the case.

Instead, python evaluates that as (9 in list) and (list == False) instead, and the latter part is never True.

You really want to use the not in operator, and avoid naming your variables list:

if 9 not in lst:
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
4

It should be:

if (9 in list) == False: print "9 is not present in list"

Thanakron Tandavas
  • 5,615
  • 5
  • 28
  • 41