Difference between if x and if x is not None
In the following cases:
test = False
test = ""
test = 0
test = 0.0
test = []
test = ()
test = {}
test = set()
the if
test will differ:
if test: #False
if test is not None: #True
This is the case because is
tests for identity, meaning
test is not None
is equivalent to
id(test) == id(None) #False
therefore
(test is not None) is (id(test) != id(None)) #True
Python `if x is not None` or `if not x is None`?
There's no performance difference, as they compile to the same bytecode:
>>> import dis
>>> dis.dis("not x is None")
1 0 LOAD_NAME 0 (x)
2 LOAD_CONST 0 (None)
4 COMPARE_OP 9 (is not)
6 RETURN_VALUE
>>> dis.dis("x is not None")
1 0 LOAD_NAME 0 (x)
2 LOAD_CONST 0 (None)
4 COMPARE_OP 9 (is not)
6 RETURN_VALUE
Stylistically, I try to avoid not x is y
, a human reader might misunderstand it as (not x) is y
. If I write x is not y
then there is no ambiguity.
Is there a difference between if not x and if x is None?
not x
will also return True
for everything that evaluates to False
in a boolean context. Some examples:
>>> x = ()
>>> not x
True
>>> x = []
>>> not x
True
>>> x = ''
>>> not x
True
>>> x = 0
>>> not x
True
>>> x is None
False
So if your code should act differently when x
is None
as opposed to x
being an empty list, tuple, string, the number zero, ... then use x == None
or x is None
instead of not x
.
How to check in python if variable is not None and greater than something in one line?
You can also use python ternary operator. In your example, this might help you. You can extend the same further too.
#if X is None, do nothing
>>> x = ''
>>> x if x and x>0 else None
#if x is not None, print it
>>> x = 1
>>> x if x and x>0 else None
1
Dealing with string values
>>> x = 'hello'
>>> x if x and len(x)>0 else None
'hello'
>>> x = ''
>>> x if x and len(x)>0 else None
>>>
python difference between (x is not None) and (y is not None) and (x and y) is not None
A programmer's wife asks him: do you want sausage or bacon for breakfast? - Yes, he responds. (a true story).
When using boolean constructs in everyday speaking we tend to skip common parts so that X(Y) @ X(Z)
becomes X @ (Y,Z)
:
Her bunny is happy and her hamster is happy (1)
is the same as
Her bunny and her hamster are happy
In programming, however, we cannot contract things like that. The first statement
bunny == happy and hamster == happy
will be true if both pets are fine. The second phrase translates literally to this:
(bunny and hamster) == happy
here, (bunny and hamster)
evaluates to
- a falsy value, if she's got no bunny
- the hamster otherwise
So (bunny and hamster) == happy
actually reads as:
She's got a bunny and her hamster is happy
which is quite different from the statement (1)
In python:
>>> happy = 1
>>> sad = 2
>>> bunny = sad
>>> hamster = happy
>>> bunny == happy and hamster == happy
False
>>> (bunny and hamster) == happy
True
>>>
not None test in Python
if val is not None:
# ...
is the Pythonic idiom for testing that a variable is not set to None
. This idiom has particular uses in the case of declaring keyword functions with default parameters. is
tests identity in Python. Because there is one and only one instance of None
present in a running Python script/program, is
is the optimal test for this. As Johnsyweb points out, this is discussed in PEP 8 under "Programming Recommendations".
As for why this is preferred to
if not (val is None):
# ...
this is simply part of the Zen of Python: "Readability counts." Good Python is often close to good pseudocode.
if A vs if A is not None:
The statement
if A:
will call A.__bool__()
(see Special method names documentation), which was called __nonzero__
in Python 2, and use the return value of that function. Here's the summary:
object.__bool__(self)
Called to implement truth value testing and the built-in operation
bool()
; should returnFalse
orTrue
. When this method is not defined,__len__()
is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither__len__()
nor__bool__()
, all its instances are considered true.
On the other hand,
if A is not None:
compares only the reference A
with None
to see whether it is the same or not.
Difference between 'not x' and 'x==None' in python
yes it can give different answers.
x == None
will call the __eq__()
method to valuate the operator and give the result implemented compared to the None
singleton.
not x
will call the __nonzero__()
(__bool__()
in python3) method to valuate the operator. The interpreter will convert x
to a boolean (bool(x)
) using the mentioned method and then inverse its returned value because of the not
operator.
x is None
means that the reference x points to the None
object, which is a singleton of type NoneType
and will valuate false in comparaisons. The is
operator tests object identity, and thus whether or not the two objects compared are the same instance of an object, and not similar objects.
What is the difference between is None and == None
The answer is explained here.
To quote:
A class is free to implement
comparison any way it chooses, and it
can choose to make comparison against
None mean something (which actually
makes sense; if someone told you to
implement the None object from
scratch, how else would you get it to
compare True against itself?).
Practically-speaking, there is not much difference since custom comparison operators are rare. But you should use is None
as a general rule.
Related Topics
How to Write Data into CSV Format as String (Not File)
Python: Mocking a Context Manager
Python 2 CSV Writer Produces Wrong Line Terminator on Windows
How to Multiply Each Element in a List by a Number
Accessing a Value in a Tuple That Is in a List
Error "Importerror: Dll Load Failed: %1 Is Not a Valid Win32 Application"
Parsing .Properties File in Python
Stratified Train/Test-Split in Scikit-Learn
Notimplementederror: Layers with Arguments in '_Init_' Must Override 'Get_Config'
How to Insert Data into a MySQL Database
Numpy: Function for Simultaneous Max() and Min()
Unbuffered Stdout in Python (As in Python -U) from Within the Program