Just found out that both syntax ways are valid.
Which is more efficient?
element not in list
Or:
not element in list
?
Just found out that both syntax ways are valid.
Which is more efficient?
element not in list
Or:
not element in list
?
U13-Forward
On
When you're doing:
not x in y
And if x is in y, it will basically simplify to not True which is:
>>> not True
False
In the other hand, x not in y is just direct checking not in
To see the timings (always pretty similar):
>>> import timeit
>>> timeit.timeit(lambda: 1 not in [1,2,3])
0.24575254094870047
>>> timeit.timeit(lambda: not 1 in [1,2,3])
0.23894292154022878
>>>
Also btw, not basically just do the opposite (if something is True, not will make it False, same point with the opposite
See not operator
They behave identically, to the point of producing identical byte code; they're equally efficient. That said,
element not in listis usually considered preferred. PEP8 doesn't have a specific recommendation onnot ... invs.... not in, but it does fornot ... isvs.... is not, and it prefers the latter:To show equivalence in performance, a quick byte code inspection: