Unless I'm crazy if None not in x
and if not None in x
are equivalent. Is there a preferred version? I guess None not in
is more english-y and therefore more pythonic, but not None in
is more like other language syntax. Is there a preferred version?
None is the pronoun form of no. None means 'not one' or 'not any'.
None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None.
None is a singleton object (there only ever exists one None ). is checks to see if the object is the same object, while == just checks if they are equivalent. But since there is only one None , they will always be the same, and is will return True.
You should use the is not operator when you need to check if a variable doesn't store a None value. When we use is or is not , we check for the object's identity. The pep 8 style guide mentions that comparison to singletons like None should always be done with is or is not , and never the equality operators.
They compile to the same bytecode, so yes they are equivalent.
>>> import dis
>>> dis.dis(lambda: None not in x)
1 0 LOAD_CONST 0 (None)
3 LOAD_GLOBAL 1 (x)
6 COMPARE_OP 7 (not in)
9 RETURN_VALUE
>>> dis.dis(lambda: not None in x)
1 0 LOAD_CONST 0 (None)
3 LOAD_GLOBAL 1 (x)
6 COMPARE_OP 7 (not in)
9 RETURN_VALUE
The documentation also makes it clear that the two are equivalent:
x not in s
returns the negation ofx in s
.
As you mention None not in x
is more natural English so I prefer to use this.
If you write not y in x
it might be unclear whether you meant not (y in x)
or (not y) in x
. There is no ambiguity if you use not in
.
The expression
not (None in x)
(parens added for clarity) is an ordinary boolean negation. However,
None not in x
is special syntax added for more readable code (there's no possibility here, nor does it make sense, to use and, or, etc in front of the in). If this special case was added, use it.
Same applies to
foo is not None
vs.
not foo is None
I find the "is not" much clearer to read. As an additional bonus, if the expression is part of a larger boolean expression, the scope of the not is immediately clear.
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