I’ve noticed that both of these work the same:
if x not in list and if not x in list.
Is there some sort of difference between the two in certain cases? Is there a reason for having both, or is it just because it’s more natural for some people to write one or the other?
Which one am I more likely to see in other people’s code?
The two forms make identical bytecode, as you can clearly verify:
so obviously they’re semantically identical.
As a matter of style, PEP 8 does not mention the issue.
Personally, I strongly prefer the
if x not in yform — that makes it immediately clear thatnot inis a single operator, and "reads like English".if not x in ymay mislead some readers into thinking it meansif (not x) in y(inverting the value of "x"), it reads a bit less like English, and it has absolutely no compensating advantages.The
if x not in yform also makes the code much more readable when you have multiple conditions. For example, consider the statementif not x in y and x in m. A casual reader might think it meansif not (x in y and x in m), but would get a surprise since the code actually executes asif (not x in y) and (x in m). So by moving thenotnext to theinoperator it belongs to, you therefore make it clear that thenot inonly applies to that particular condition, rather than all of them.Therefore,
if x not in y and x in mhas multiple readability benefits and is easier to understand regardless of programming experience. Furthermore,not inis the official name of the "not in" bytecode operator (as seen in the disassembly above), regardless of how the user writes it, which further confirms thatnot inis Python’s preferred style.Let’s also consider a similar statement. The
is notcondition. If you attempt to writeif not x is True, it becomes really obvious how silly and backwards that pattern is. Neither of them make any sense logically, but it becomes extra obvious in thatis notexample.In short,
if X is not Yandif X not in Yare the preferred ways of writing these kinds of Python statements.