4

Hi can someone shed light on the mechanics of working "in" operator in Python.

I'm now dealing with examples below:

print ('a' not in ['a', 'b'])  # outputs False
print (not 'a' in ['a', 'b'])  # outputs False   --   how ???

print ('c' not in ['a', 'b'])  # outputs True
print (not 'c' in ['a', 'b'])  # outputs True


print (not 'a')   # outputs False
# ok is so then...
print (not 'a' in ['b', False])   # outputs True --- why ???

I'm now in wonder how it can be so. If someone knows, please share your knowledge. Thanks =)

Alex
  • 591
  • 1
  • 6
  • 13
  • 5
    `a not in` and `not a in` are equal – Tim Oct 28 '14 at 16:54
  • 2
    Note that the python styleguide says you should use `a not in`, even though they do the same. – Tim Oct 28 '14 at 16:58
  • you could easily change it to `(not 'a') in ['b', False]` which would give you the answer you apparently expect (since parens always denote higher precedence) – Joran Beasley Oct 28 '14 at 17:00
  • The [peephole optimizer](https://github.com/python/cpython/blob/master/Python/peephole.c#L437) converts statements like `not a in b` to `a not in b`. So, that's another reason to use `not in`, and it is much readable as well IMO. – Ashwini Chaudhary Oct 28 '14 at 17:04

3 Answers3

9

in has higher precedence than not. As such, the containment check is performed and then the result is negated if required. 'a' is not in ['b', False], and the resultant False is negated to result in True.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
2

the not keyword basically "reverses" the boolean returned here.

For the first example, a is in the array, so that's true, but not true is false. So false.

For the second example, a is not in the array, so that's false, but not false is true. So true.

Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
-1

print (not 'a' in ['a', 'b'])

break it down like this:

not 'a' evaluates to False by itself (because anything is considered True except 0,None,False,empty lists, and empty dictionaries )

and false is not in ['a','b'] so False in ['a','b'] evaluates to False

and on the last one not 'a' evaluates to False so False in ['b', False] evaluates to True

TehTris
  • 3,139
  • 1
  • 21
  • 33