1

In the application I am currently developing in python3, I often use statements like

elem_in_list = elem in list

But sometimes I need to check whether the element is not in the list. Is there a performance differece between

elem_not_in_list = not elem in list

and

elem_not_in_list = elem not in list

or is it just the same? Is one of the notations preferable?

Richard Neumann
  • 2,986
  • 2
  • 25
  • 50
  • Why not `timeit` and find out? – jonrsharpe Aug 06 '14 at 07:28
  • Very closely related, but not quite identical: http://stackoverflow.com/questions/2710940/python-if-x-is-not-none-or-if-not-x-is-none. I'm not sure whether there's an existing question for `not in`; these little words are hard to search for. – user2357112 Aug 06 '14 at 07:58

1 Answers1

14

These expressions compile to the exact same bytecode, so they're exactly equally efficient. not in tends to be more readable, but it's a matter of opinion.

>>> import dis
>>> def f(x, y):
...     return not x in y
...
>>> def g(x, y):
...     return x not in y
...
>>> dis.dis(f)
  2           0 LOAD_FAST                0 (x)
              3 LOAD_FAST                1 (y)
              6 COMPARE_OP               7 (not in)
              9 RETURN_VALUE
>>> dis.dis(g)
  2           0 LOAD_FAST                0 (x)
              3 LOAD_FAST                1 (y)
              6 COMPARE_OP               7 (not in)
              9 RETURN_VALUE
user2357112
  • 260,549
  • 28
  • 431
  • 505