Skip to content Skip to sidebar Skip to footer

Python Operator, No Operator For "not In"

This is a possibly silly question, but looking at the mapping of operators to functions I noticed that there is no function to express the not in operator. At first I thought this

Solution 1:

Another function is not necessary here. not in is the inverse of in, so you have the following mappings:

obj in seq => contains(seq, obj)

obj not in seq => not contains(seq, obj)

You are right this is not consistent with is/is not, since identity tests should be symmetrical. This might be a design artifact.


Solution 2:

You may find the following function and disassembly to be helpful for understanding the operators:

>>> def test():
        if 0 in (): pass
        if 0 not in (): pass
        if 0 is (): pass
        if 0 is not (): pass
        return None

>>> dis.dis(test)
  2           0 LOAD_CONST               1 (0) 
              3 LOAD_CONST               2 (()) 
              6 COMPARE_OP               6 (in) 
              9 POP_JUMP_IF_FALSE       15 
             12 JUMP_FORWARD             0 (to 15) 

  3     >>   15 LOAD_CONST               1 (0) 
             18 LOAD_CONST               3 (()) 
             21 COMPARE_OP               7 (not in) 
             24 POP_JUMP_IF_FALSE       30 
             27 JUMP_FORWARD             0 (to 30) 

  4     >>   30 LOAD_CONST               1 (0) 
             33 LOAD_CONST               4 (()) 
             36 COMPARE_OP               8 (is) 
             39 POP_JUMP_IF_FALSE       45 
             42 JUMP_FORWARD             0 (to 45) 

  5     >>   45 LOAD_CONST               1 (0) 
             48 LOAD_CONST               5 (()) 
             51 COMPARE_OP               9 (is not) 
             54 POP_JUMP_IF_FALSE       60 
             57 JUMP_FORWARD             0 (to 60) 

  6     >>   60 LOAD_CONST               0 (None) 
             63 RETURN_VALUE         
>>> 

As you can see, there is a difference in each operator; and their codes (in order) are 6, 7, 8, and 9.


Post a Comment for "Python Operator, No Operator For "not In""