- Python ‘is not none’ syntax explained
- Conclusion
- Take your skills to the next level ⚡️
- About
- Search
- Check not none python
- # Check if a Variable is or is not None in Python
- # Using is and is not vs the equality (==) operators
- # There is only one instance of None in a Python program
- # Checking for None vs checking for truthyness
- # Check if multiple variables are not None in Python
- # Check if multiple variables are not None using in operator
- # Conclusion
- # Additional Resources
Python ‘is not none’ syntax explained
The is not operator returns True when the left-hand operator is not equal to the right-hand operator:
In the above example, the variable x is assigned the value of None . The if statement checks if x is not equal to None by using the is not operator.
In this case, the code will print x is None because x is assigned the value of None .
You can also use the equality comparison operator != to replace the is not operator as follows:
Since None is a singleton object, it is possible to use the is not operator to check if a variable is None instead of using the != operator.
The is or is not operator checks for object identity, which is faster than the == or != operator that checks for the equality of the object values.
What’s more, the == result is always True when is returns True (but not the opposite)
Let’s see an example that shows the differences:
When you check if the value of x and y is equal using the == operator, Python returns True because they have the same value of [1, 2, 3] .
But when you check if the object identity of x is the same as y , Python returns False because they are different objects, stored at different memory points.
You can use the id() function to check for the identification number that points to the object in memory as follows:
The ID numbers may be different when you run the code above, but the x and y numbers will never be the same.
On the other hand, the ID numbers for the None object is always the same:
It’s recommended to use the is not operator instead of != operator when checking for None .
Next, you can also use the is not None operator in a function that returns a value only if the input is not None:
In this example, the function add_numbers takes two arguments and returns the sum of the two numbers if both arguments are not None . Otherwise, it returns None .
Finally, it’s also possible to use the None keyword in the condition of a ternary operator as follows:
Conclusion
To conclude, the is not None syntax is a way to check if a variable or expression is not equal to None in Python.
Combined with the if statement, this logic can be useful in situations where you have a function that requires a certain variable to be not None .
It can also be used when you want to return a value only if the input is not None . It’s recommended to use the is operator instead of the == operator when checking for None .
Take your skills to the next level ⚡️
I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!
About
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.
Search
Type the keyword below and hit enter
Check not none python
Last updated: Feb 18, 2023
Reading time · 7 min
# 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.
Copied!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.
Copied!my_var = 'example' # ✅ Check if 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 .
Copied!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 .
Copied!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.
Copied!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.
# 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.
Copied!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)
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 ( == ).
Copied!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.
Copied!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.
Copied!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 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.
Copied!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.
Copied!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.
Copied!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.
Copied!var_1 = 'example' if var_1 is not None: print('The variable is NOT None') print(var_1 is not None) # 👉️ True
# Checking for None vs checking for truthyness
You might also see examples online that check for truthyness.
Copied!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:
- 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).
Copied!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 .
Copied!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:
- Wrap the variables in a list.
- Iterate over the list.
- Check if each variable is not None .
Copied!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).
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.
Copied!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.
There are some very rare cases where using equals and not equals to check for 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.
Copied!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.
Copied!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 .
# 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.