Check if a Variable is or is not None in Python

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
7 min

banner

# Check if a Variable is or is not None in Python

Use the is operator to check if a variable is None in Python, e.g. if my_var is None:.

The is operator will return True if the variable is None and False otherwise.

main.py
my_var = None # โœ… Check if a variable is None if my_var is None: # ๐Ÿ‘‡๏ธ this runs print('variable is None')

check if variable is none in python

The code for this article is available on GitHub

If you need to check if a variable is NOT None, use the is not operator.

main.py
my_var = 'example' # โœ… Check if a variable is NOT None if my_var is not None: # ๐Ÿ‘‡๏ธ this runs print('variable is not None')

check if variable is not none

The is identity operator returns True if the values on the left-hand and right-hand sides point to the same object and should be used when checking for singletons like None.

main.py
var_1 = None print(var_1 is None) # ๐Ÿ‘‰๏ธ True var_2 = 'example' print(var_2 is None) # ๐Ÿ‘‰๏ธ False

When we use is, we check for the object's identity.

Similarly, the is not operator should be used when you need to check if a variable is not None.

main.py
var_1 = 'example' print(var_1 is not None) # ๐Ÿ‘‰๏ธ True var_2 = None print(var_2 is not None) # ๐Ÿ‘‰๏ธ False

If you need to check if a variable exists and has been declared, use a try/except statement.

main.py
try: does_this_exist print('variable exists') except NameError: print('variable does NOT exist')

check if variable exists using try except

The code for this article is available on GitHub

The try statement tries to access the variable and if it doesn't exist, the else block runs.

# Using is and is not vs the equality (==) operators

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.

main.py
var_1 = None # โœ… correct way of checking for None print(var_1 is None) # โœ… correct way of checking if not None print(var_1 is not None) # ---------------------------------------- # โ›”๏ธ incorrect way of checking for None print(var_1 == None) # โ›”๏ธ incorrect way of checking if not None print(var_1 != None)
The code for this article is available on GitHub
Use the equality operators (equals == and not equals !=) when you need to check if a value is equal to another value, e.g. 'hello' == 'hello'.

Here is an example that better illustrates checking for identity (is) vs checking for equality (==).

main.py
first_list = ['a', 'b', 'c'] second_list = first_list # ๐Ÿ‘ˆ๏ธ same list as above print(first_list is second_list) # ๐Ÿ‘‰๏ธ True print(first_list == second_list) # ๐Ÿ‘‰๏ธ True

We declared 2 variables that store the same list.

We set the second variable to the first, so both variables point to the same list in memory.

Now, let's create a shallow copy of the list and assign it to the second variable.

main.py
first_list = ['a', 'b', 'c'] second_list = first_list.copy() # ๐Ÿ‘ˆ๏ธ copy created # ๐Ÿ‘‡๏ธ Identity check print(first_list is second_list) # ๐Ÿ‘‰๏ธ False # ๐Ÿ‘‡๏ธ Equality check print(first_list == second_list) # ๐Ÿ‘‰๏ธ True

identity vs equality checking

Notice that the identity check failed.

Even though the two lists store the same values, in the same order, they point to different locations in memory (they are not the same object).

When we use the double equals operator, Python calls the __eq__() method on the object.

In other words, x==y calls x.__eq__(y). In theory, this method could be implemented differently, so checking for None with the is operator is more direct.

You can use the id() function to get the identity of an object.

main.py
first_list = ['a', 'b', 'c'] print(id(first_list)) # ๐Ÿ‘‰๏ธ 139944523741504 second_list = first_list.copy() print(id(second_list)) # ๐Ÿ‘‰๏ธ 139944522293184 print(id(first_list) == id(second_list)) # ๐Ÿ‘‰๏ธ False
The code for this article is available on GitHub
The function returns an integer that is guaranteed to be unique and constant for the object's lifetime.

The id() function returns the address of the object in memory in CPython.

If the two variables refer to the same object, the id() function will produce the same result.

main.py
my_first_list = ['a', 'b', 'c'] print(id(my_first_list)) # ๐Ÿ‘‰๏ธ 140311440685376 my_second_list = my_first_list print(id(my_second_list)) # ๐Ÿ‘‰๏ธ 140311440685376 print(id(my_first_list) == id(my_second_list)) # ๐Ÿ‘‰๏ธ True
Want to learn more about working with None in Python? Check out these resources: Convert None to Empty string or an Integer in Python,How to Return a default value if None in Python.

# There is only one instance of None in a Python program

Passing a None value to the id() function is always going to return the same result because there is only one instance of None in a Python program.

main.py
print(id(None)) # ๐Ÿ‘‰๏ธ 9817984 print(id(None)) # ๐Ÿ‘‰๏ธ 9817984
The code for this article is available on GitHub

Since there is only one instance of None in a Python program, the correct way of checking for None is to use the is operator.

main.py
var_1 = None if var_1 is None: print('The variable is None') print(var_1 is None) # ๐Ÿ‘‰๏ธ True

use is operator when checking for none

Similarly, the correct way of checking if a variable is not None is to use the is not operator.

main.py
var_1 = 'example' if var_1 is not None: print('The variable is NOT None') print(var_1 is not None) # ๐Ÿ‘‰๏ธ True

check for not none using is not none

# Checking for None vs checking for truthyness

You might also see examples online that check for truthyness.

main.py
var_1 = None # ๐Ÿ‘‡๏ธ Checks if the variable stores a falsy value if not var_1: print('The variable stores a falsy value')

checking for truthyness

The code for this article is available on GitHub

The code sample checks if the variable stores a falsy value. It doesn't explicitly check for None.

This is very different than explicitly checking if a variable stores a None value because many falsy values are not None.

The falsy values in Python are:

  • constants defined to be falsy: None and False.
  • 0 (zero) of any numeric type
  • empty sequences and collections: "" (empty string), () (empty tuple), [] (empty list), {} (empty dictionary), set() (empty set), range(0) (empty range).

All other values are truthy.

None is NOT equal to an empty string, False, 0, or any other of the falsy values.

In other words, the following if statement runs if the var_1 variable stores any of the aforementioned falsy values (not just None).

main.py
var_1 = "" # ๐Ÿ‘‡๏ธ Checks if the variable stores a falsy value if not var_1: # ๐Ÿ‘‡๏ธ this runs print('The variable stores a falsy value')

The variable stores an empty string and empty strings are falsy values, so the if block runs.

If you check if a variable is truthy, you are checking if the variable is not any of the aforementioned falsy values, not just None.

main.py
var_1 = "example" # ๐Ÿ‘‡๏ธ Checks if the variable stores a truthy value if var_1: print('The variable stores a truthy value')

Another common thing you might have to do is check if multiple variables are not None.

# Check if multiple variables are not None in Python

To check if multiple variables are not None:

  1. Wrap the variables in a list.
  2. Iterate over the list.
  3. Check if each variable is not None.
main.py
a = 'a' b = 'b' c = 'c' if all(item is not None for item in [a, b, c]): print('Multiple variables are NOT None') else: print('At least one of the variables stores a None value')

check if multiple variables are not none

The code for this article is available on GitHub

If you need to check if multiple variables are None, you would use the is operator instead of is not.

We used square brackets to add the variables to a list and used a generator expression to iterate over the list.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we check if the current list item is not None and return the result.

The last step is to pass the generator object to the all() function.

The all() built-in function takes an iterable as an argument and returns True if all elements of the iterable are truthy (or the iterable is empty).

If all of the variables are not None, the all() function will return True, otherwise, False is returned.

# Check if multiple variables are not None using in operator

You can also check if multiple variables are not None using the in operator.

main.py
a = 'a' b = 'b' c = 'c' if None not in (a, b, c): # ๐Ÿ‘‡๏ธ this runs print('Multiple variables are NOT None')

check if multiple variables are not none using in operator

The code for this article is available on GitHub

This approach looks much simpler than the previous one.

However, the in and not in operators check for equality, e.g. None != a, None != b, etc.

As previously noted, this is not a good practice in Python as it is recommended to check for None using the is keyword.

There are some very rare cases where using equals and not equals to check forNone might lead to confusing behavior, so the PEP8 style guide recommends using is and is not when testing for None.

The in operator tests for membership. For example, x in l evaluates to True if x is a member of l, otherwise it evaluates to False.

x not in l returns the negation of x in l.

An alternative approach is to use the and operator multiple times.

main.py
a = 'a' b = 'b' c = 'c' if a is not None and b is not None and c is not None: print('Multiple variables are NOT None')

check if multiple variables are not none using and operator

This is generally not recommended, as it is quite repetitive and difficult to read.

The if statement first checks if the a variable is not None.

If the condition is met, the if statement short-circuits returning False without checking any of the following conditions.

The best way to check if multiple variables are not None is to use the all() function.

main.py
a = 'a' b = 'b' c = 'c' if all(item is not None for item in [a, b, c]): print('Multiple variables are NOT None') else: print('At least one of the variables stores a None value')
The code for this article is available on GitHub

The all() function is not as manual as using the and operator and allows us to check for None using is.

# Conclusion

Always use the is operator to check if a variable stores a None value in Python.

Similarly, you should use the is not operator to check if a variable is not None.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev