Skip to content

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.

Check if a variable is not None in Python

python
if x is not None:
    # do something

It 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

python
if not x is None:  # not recommended
    # do something

<div class="alert alert-info flex not-prose"> Watch a course 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

python
if x:
    # do something

As None is considered as a False value in python, The above statement will also check if x is not None

Dual-run preview — compare with live Symfony routes.