Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When checking if an item does not exist in a list, why doesn't this code work - if item in list == False: [duplicate]

Tags:

python

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?

like image 553
Raghav Mujumdar Avatar asked Nov 30 '22 13:11

Raghav Mujumdar


1 Answers

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:
like image 189
Martijn Pieters Avatar answered Dec 06 '22 19:12

Martijn Pieters