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 expression not x means if x is True or False. In Python, if a variable is a numeric zero or empty, or a None object then it is considered as False, otherwise True. In that case, as x = 10 so it is True.
Python 'in' operator is used to check if a value exists in a sequence or not. It evaluates to True if it finds the variable in the specified sequence and False otherwise. Python 'not in' operator evaluates to True if it does not finds a variable in the specified sequence and False otherwise.
The two forms make identical bytecode, as you can clearly verify:
>>> import dis >>> dis.dis(compile('if x not in d: pass', '', 'exec')) 1 0 LOAD_NAME 0 (x) 3 LOAD_NAME 1 (d) 6 COMPARE_OP 7 (not in) 9 JUMP_IF_FALSE 4 (to 16) 12 POP_TOP 13 JUMP_FORWARD 1 (to 17) >> 16 POP_TOP >> 17 LOAD_CONST 0 (None) 20 RETURN_VALUE >>> dis.dis(compile('if not x in d: pass', '', 'exec')) 1 0 LOAD_NAME 0 (x) 3 LOAD_NAME 1 (d) 6 COMPARE_OP 7 (not in) 9 JUMP_IF_FALSE 4 (to 16) 12 POP_TOP 13 JUMP_FORWARD 1 (to 17) >> 16 POP_TOP >> 17 LOAD_CONST 0 (None) 20 RETURN_VALUE
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 y
form -- that makes it immediately clear that not in
is a single operator, and "reads like English". if not x in y
may mislead some readers into thinking it means if (not x) in y
, reads a bit less like English, and has absolutely no compensating advantages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With