-3
if not 7 in [5, 6, 7]:
     # something

if 7 not in [5, 6, 7]:
    # something

Which is faster?

serv-inc
  • 35,772
  • 9
  • 166
  • 188
Camile
  • 107
  • 5
  • 2
    Welcome to StackOverflow. This is the kind of question you could easily test for yourself. Have you tried `timeit` or some other mechanism to test both those lines on your machine? – Rory Daulton Feb 21 '19 at 11:36
  • Only a matter of readability and personal choice. – DirtyBit Feb 21 '19 at 11:37
  • When in doubt, *measure*. Run a loop a couple of million times for each variant, and measure the total time of the loops. Compare the results. See e.g. [this QA](https://stackoverflow.com/questions/2866380/how-can-i-time-a-code-segment-for-testing-performance-with-pythons-timeit) for examples on how to do the timing. – Some programmer dude Feb 21 '19 at 11:37

2 Answers2

4

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.

tobias_k
  • 81,265
  • 12
  • 120
  • 179
1

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.

Óscar López
  • 232,561
  • 37
  • 312
  • 386