How to check if multiple variables are not None in Python
In this tutorial, we are going to learn about how to check if a multiple variables are not none in Python with the help of examples.
Note: Not None means there is some data stored inside the variables.
Consider, that we have the following variables in our code:
x = 1
y = 2
z = 3
Now, we need to check the above variables are not None.
Checking if multiple variables are not None
To check if multiple variables are not None, we can use the built-in all()
function in Python.
The all()
function returns True if all items in the iterable are true. Otherwise, it returns false.
Here is an example:
x = 1
y = 2
z = 3
if all(item is not None for item in [x, y, z]):
print('Multiple variables are not None')
else:
print('Some of the variables are None')
Output:
'Multiple variables are not None'
In the above code,
-
We have first added the variables into the list.
-
Then iterated over the list using
in
operator. -
On each iteration, we have checked if the
item is not None
.
Finally, the all()
function returns True
if the all items in the list returns true, otherwise false is returned.
If it returns True
then it should prints the Multiple variables are not None
, if at least one of the variables is None then it returns False
and prints Some of the variables are None
.
Example 2: Some of the variables are none
x = 1
y = 2
z = None
if all(item is not None for item in [x, y, z]):
print('Multiple variables are not None')
else:
print('Some of the variables are None')
Output:
'Some of the variables are None'
In the above code, it prints “Some of the variables are None” because the variable z
is assigned to None.