How to check if variable is None in Python

Feb 08, 2024#python#operators

In Python, None is a special data type that represents the absence of any value or object. It is not the same as 0, False, or an empty string. None is the only instance of the NoneType class, and it can be compared with the is operator.

Using is or == operator

The is operator is used to test object identity. It checks whether two variables refer to the exact same object in memory. This is different from the == operator, which tests whether two objects have the same values.

Using the is operator when checking for None is recommended because None is a singleton object. In Python, there is only one None object, and all references to None point to the same memory location. The is operator checks for object identity, so it’s the most appropriate way to test if a variable is None.

x = None

# Using `is` to check for None
if x is None:
    print("x is None")

# Using `==` to check for None (not recommended)
if x == None:
    print("x is None")

While both is and == may work in this specific case, using is is considered more Pythonic and is a better practice. Using == for None comparisons might lead to unexpected behavior in certain situations, especially when dealing with custom objects or overloaded equality operators.

Using is not or != operator

To check if a variable is not None in Python, you can use the is not operator or the != operator. Both is not and != can be used in this context. However, using is not is generally recommended when checking for None because, as mentioned earlier.

# Using `is not` operator
my_variable = 42

if my_variable is not None:
    print("my_variable is not None")
else:
    print("my_variable is None")

# Using `!=` operator
if my_variable != None:
    print("my_variable is not None")
else:
    print("my_variable is None")