Reputation: 3361
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?
Upvotes: 1
Views: 513
Reputation: 280564
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
Upvotes: 14