1

So I thought I found a typo in code I was working on. I thought 'not' would operate on string "eta" and make it False and False is not in the List,so nothing should print - however in both the below case "Eta not found" is printed. I guess this has something to do with order of evaluation that both statements are equal, right?

if not "eta" in ["alpha", "beta", "gamma"]:
   print ("Eta not found")

if "eta" not in ["alpha", "beta", "gamma"]:
   print ("Eta not found")
physicist
  • 844
  • 1
  • 12
  • 24

2 Answers2

3

The result is the same in both cases because slightly different syntax for the same statement should result in equal results, right? And

if not "eta" in ["alpha", "beta", "gamma"]:

is the same as:

if not ("eta" in ["alpha", "beta", "gamma"]):

which is equivalent to:

if ("eta" not in ["alpha", "beta", "gamma"]):

meissner_
  • 556
  • 6
  • 10
2

in has a higher precedence than not, so not x in a means not (x in a). Keep in mind two things though.

  • not in is a new operator by itself, not just a conjuction of not and in. Actually, it couldn't be: the not operator has to be followed by an expression, not by another operator.
  • the python interpreter seems to convert not x in a to x not in a
blue_note
  • 27,712
  • 9
  • 72
  • 90