Check if variable is none python

How To Check If A Variable Is None In Python

If you have trouble and don’t know how to check if a variable is None in Python, don’t miss our article. We will give you some solutions for checking if a variable is none. Let’s go on now.

Check the type of any object in Python

In Python, we can check the type of any object by the following command:

myVar = < "sky": "blue", "tree": "green", "sun": "yellow" >print("myVar has:", type(myVar))

As you can see, the type() function returns the object’s class type. You can use the type() function to check if a variable is None. For instance:

myVar = None print("myVar has:", type(myVar))

Now, we will show you other alternative ways to check if a variable is None in Python.

Check if a variable is None in Python

Method 1: Using the “is” operator

The “Is” operator is used to check if variables point to the same object. The result returns true if variables belong to one object and false otherwise. Look at the following example:

# Declare variable myVar = None myVar = None print("myVar has:", type(myVar)) print(myVar is None)

Another way:

# Declare variable myVar = None myVar = None print("myVar has:", type(myVar)) print(type(myVar) is type(None))

Method 2: Using “==” operator

This operator compares the operands’ values of two variables. The result returns true if they are equal and false otherwise.

You can directly check the value of the variable like this:

# Declare variable myVar = None myVar = None print("myVar has:", type(myVar)) print(myVar == None)

Also, you can check the value of the variables’ type.

# Declare variable myVar = None myVar = None print("myVar has:", type(myVar)) print(type(myVar) == type(None))

Method 3: Using the isinstance() function

The function checks if the object’s variable is an instance of a special class. The result is a boolean type

# Declare variable myVar = None myVar = None print("myVar has:", type(myVar)) print( isinstance(myVar, type(None)))

Summary

Our tutorial gives you some explanations and solutions to check if a variable is None in Python. Objectively, we strongly recommend using the type() function to check the variable type as the most effective way. Hope our article is helpful for you.

My name is Robert Collier. I graduated in IT at HUST university. My interest is learning programming languages; my strengths are Python, C, C++, and Machine Learning/Deep Learning/NLP. I will share all the knowledge I have through my articles. Hope you like them.

Name of the university: HUST
Major: IT
Programming Languages: Python, C, C++, Machine Learning/Deep Learning/NLP

Источник

Check if variable is none python

Last updated: Feb 18, 2023
Reading time · 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.

Copied!
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

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')

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 .

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')

check if variable exists using try except

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

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.

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.

Читайте также:  Tostring in java with example

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

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.

Copied!
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.

Copied!
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 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:

  1. Wrap the variables in a list.
  2. Iterate over the list.
  3. 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')

check if multiple variables are not none

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

Читайте также:  Выпадающий блок при клике css

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')

check if multiple variables are not none using in operator

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')

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.

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.

Источник

Оцените статью