if not 7 in [5, 6, 7]:
# something
if 7 not in [5, 6, 7]:
# something
Which is faster?
if not 7 in [5, 6, 7]:
# something
if 7 not in [5, 6, 7]:
# something
Which is faster?
They are exactly the same, and thus take the same amount of time. not in
is just syntactic sugar. Using the dis
module, we can see that both result in the same bytecode:
>>> dis.dis("not x in y")
1 0 LOAD_NAME 0 (x)
2 LOAD_NAME 1 (y)
4 COMPARE_OP 7 (not in)
6 RETURN_VALUE
>>> dis.dis("x not in y")
1 0 LOAD_NAME 0 (x)
2 LOAD_NAME 1 (y)
4 COMPARE_OP 7 (not in)
6 RETURN_VALUE
Even adding parentheses as not (x in y)
does not change that, unless, of course, you add more to the parentheses:
>>> dis.dis("not (x in y)")
1 0 LOAD_NAME 0 (x)
2 LOAD_NAME 1 (y)
4 COMPARE_OP 7 (not in)
6 RETURN_VALUE
>>> dis.dis("not (x in y or z)")
1 0 LOAD_NAME 0 (x)
2 LOAD_NAME 1 (y)
4 COMPARE_OP 6 (in)
6 JUMP_IF_TRUE_OR_POP 10
8 LOAD_NAME 2 (z)
>> 10 UNARY_NOT
12 RETURN_VALUE
Tested with both, Python 3.6.7 and 2.7.15.
It's exactly the same, there is no difference at all. The standard operator is in fact not in
(see the docs), the not 7 in
form will get automatically transformed to 7 not in
.
So the recommended way is if 7 not in [5, 6, 7]
, that's a straight use of the operator and also has improved readability.