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 inseq => contains(seq, obj)
obj not inseq => 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:
>>> deftest():
if0in (): passif0notin (): passif0is (): passif0isnot (): passreturnNone>>> dis.dis(test)
20 LOAD_CONST 1 (0)
3 LOAD_CONST 2 (())
6 COMPARE_OP 6 (in)
9 POP_JUMP_IF_FALSE 1512 JUMP_FORWARD 0 (to 15)
3 >> 15 LOAD_CONST 1 (0)
18 LOAD_CONST 3 (())
21 COMPARE_OP 7 (notin)
24 POP_JUMP_IF_FALSE 3027 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 4542 JUMP_FORWARD 0 (to 45)
5 >> 45 LOAD_CONST 1 (0)
48 LOAD_CONST 5 (())
51 COMPARE_OP 9 (isnot)
54 POP_JUMP_IF_FALSE 6057 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""