Python `if x is not None` or `if not x is None`?
The proper way to check if a variable x is not None in Python is to use if x is not None.
The proper way to check if a variable x is not None in Python is to use if x is not None.
Check if a variable is not None in Python
if x is not None:
# do somethingIt is not recommended to use if not x is None as it is less readable, and the double negation can be confusing.
Check if a variable is not None in Python with a less readable approach
if not x is None: # not recommended
# do something
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
It is also common and more pythonic to use if x instead of if x is not None
Check if a variable is not None in Python with a more pythonic way
if x:
# do somethingAs None is considered as a False value in python, The above statement will also check if x is not None