Borislav Hadzhiev
Last updated: Jul 15, 2022
Check out my new book
To check if multiple variables are not None:
None
.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')
We used square brackets to add the variables to a list and used a generator expression to iterate over the list.
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.An alternative approach is to use the in
operator.
To check if multiple variables are not None:
not in
operator to check if None
is not a member of the sequence.None
, then the variables are not None
.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.
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 hard to read.
if
statement first checks if the a
variable is not None
. If it it, the if
statement short-circuits returning False
without checking any of the following conditions.The expression x and y
returns the value to the left if it's falsy, otherwise
the value to the right is returned.
result = False and 'hello' print(result) # 👉️ False
All values that are not truthy are considered falsy. 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).So if the value to the left is any of the aforementioned falsy values, the value to the left is returned.
all()
function to check if multiple variables are not None
, as this approach doesn't have any edge cases and is quite readable.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')