Last updated: Apr 8, 2024
Reading timeยท7 min
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.
my_var = None # โ Check if a variable is None if my_var is None: # ๐๏ธ this runs print('variable is None')
If you need to check if a variable is NOT None
, use the is not
operator.
my_var = 'example' # โ Check if a variable is NOT None if my_var is not None: # ๐๏ธ this runs print('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
.
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
.
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.
try: does_this_exist print('variable exists') except NameError: print('variable does NOT exist')
The try
statement tries to access the variable and if it doesn't exist, the
else
block runs.
is
and is not
vs the equality (==) operatorsThe
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.
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)
==
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 (==
).
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.
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
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.
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 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.
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
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.
print(id(None)) # ๐๏ธ 9817984 print(id(None)) # ๐๏ธ 9817984
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.
var_1 = None if var_1 is None: print('The variable is None') print(var_1 is None) # ๐๏ธ True
Similarly, the correct way of checking if a variable is not None is to use the
is not
operator.
var_1 = 'example' if var_1 is not None: print('The variable is NOT None') print(var_1 is not None) # ๐๏ธ True
You might also see examples online that check for truthyness.
var_1 = None # ๐๏ธ Checks if the variable stores a falsy value if not var_1: print('The variable stores a falsy value')
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:
None
and False
.0
(zero) of any numeric type""
(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).
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
.
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
.
To check if multiple variables are not None:
None
.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')
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).
None
, the all()
function will return True
, otherwise, False
is returned.in
operatorYou can also check if multiple variables are not None
using the in
operator.
a = 'a' b = 'b' c = 'c' if None not in (a, b, c): # ๐๏ธ this runs print('Multiple variables are NOT None')
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.
None
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.
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')
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.
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 all()
function is not as manual as using the and
operator and allows us
to check for None
using is
.
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
.
You can learn more about the related topics by checking out the following tutorials: