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?

2
  • Why not timeit and find out? Commented Aug 6, 2014 at 7:28
  • Very closely related, but not quite identical: stackoverflow.com/questions/2710940/…. I'm not sure whether there's an existing question for not in; these little words are hard to search for. Commented Aug 6, 2014 at 7:58

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I did not know about dis. This seems very useful.