Check if a variable is None in Python

In this Python tutorial, I will explain how to check if a variable is None in Python. We will see many different methods to check if the variable is None with examples.

In Python, a variable serves as a reference or name that points to a location in memory where data or an object is stored. This allows us to store, modify, and retrieve the data or object using the variable’s name.

For instance,

Country = "United states of America"
States = 50

Here, Country and States are the variables in Python with string and int as values respectively.

For more details, read: Variable in Python

When working with Python, we might come across situations where we need to check if a variable is set to the value None. The None value in Python represents the absence of a value or a null value. When a variable is assigned the value None, it means that the variable doesn’t currently reference any object or value.

For instance,

Country = "United states of America"
States = 50
Population = None

Here, Population is a variable in Python with a None value.

Methods to check if a variable is None in Python

There are six different methods in Python to check if a variable is None.

  • The is Operator
  • The == Operator
  • The not Keyword
  • Try-Except Block
  • Lambda Function
  • The isinstance() Method

Let’s see them one by one with illustrative examples:

Method 1: Python check if variable is None using the ‘is’ operator

The ‘is‘ operator in Python checks for variable identity. It determines if two variables reference the same memory location. Since None is a singleton in Python, using ‘is’ is the most direct way to check if the variable is None Python.

Scenario: A national park in Arizona is updating its database on various wildlife. They want to ensure the last sighting date for several animals is recorded in Python.

bear_last_sighting = None
eagle_last_sighting = "2023-08-20"
coyote_last_sighting = "2023-08-15"

if bear_last_sighting is None:
    print("The last sighting date for the bear isn't recorded.")
if eagle_last_sighting is None:
    print("The last sighting date for the eagle isn't recorded.")
if coyote_last_sighting is None:
    print("The last sighting date for the coyote isn't recorded.")

The output is: If a last sighting date is None, it means the date hasn’t been logged in the system for that particular animal. In this scenario, the date for the bear’s last sighting hasn’t been recorded.

The last sighting date for the bear isn't recorded.
check if variable is None Python

This way use the ‘is’ operator to check if a variable is None in Python.

Method 2: Check if a variable is None in Python using the ‘==’ operator

The ‘==‘ operator (equality operator) checks for value equality. It determines if two Variables have the same value, even if they are different instances.

Scenario: In California, a utility company checks if a house’s electricity meter reading has been updated this month.

meter_reading = None
if meter_reading == None:
    print("Meter reading for this month not updated.")

The output is:

Meter reading for this month not updated.
Python check if None variable

This way we can use the == operator for checking if the Python variable is None.

Method 3: Python variable check if None using not keyword

The not keyword inverts a boolean expression. In Python, None is inherently falsy. However, other values like empty strings or zeros are also falsy, so this check isn’t exclusive to None.

Scenario: An event manager in Las Vegas checks if seating arrangements for multiple VIP guests are in place through Python.

elton_seating = None
taylor_seating = "Table 5"

if not elton_seating:
    print("Seating for Elton not arranged.")
if not taylor_seating:
    print("Seating for Taylor not arranged.")

The output is: The manager checks if each VIP’s seating is None.

Seating for Elton not arranged.
Python variable check if None

This way we can use not keyword for Python variable check if None.

Method 4: Check if Python Variable is None using try-except block

A try-except block in Python attempts to execute a block of code in the try section. If an exception occurs, it’s caught in the except section. Here, a TypeError could indicate a None value.

Scenario: A bank in Chicago is calculating interest for multiple accounts but is unsure if the interest rates for all accounts have been set. So, they are using try except in Python.

alice_rate = None
bob_rate = 3.5

try:
    alice_interest = 1000 * alice_rate
    print(alice_interest)
except TypeError:
    print("Interest rate for Alice not set.")

try:
    bob_interest = 1000 * bob_rate
    print(bob_interest)
except TypeError:
    print("Interest rate for Bob not set.")

The output is: When multiplying Alice’s principal amount with her interest rate (which is None), a Python TypeError occurs, signaling that the rate hasn’t been set.

Interest rate for Alice not set.
3500.0
how to check if variable is None Python

This way we can use try except to check Python variable is None.

Method 5: Use the lambda function to check if the variable is None

A lambda function in Python is an inline, anonymous function. It can be used to concisely define simple functions. Here, it checks each entry in the Python list against None.

Scenario: A health department in Seattle tracks daily flu cases and wants to identify days with no reported cases.

daily_cases = {"Mon": 10, "Tue": None, "Wed": 15, "Thu": None, "Fri": 20}
no_case_days = list(filter(lambda day: daily_cases[day] is None, daily_cases))
print(f"Days with no reported cases: {no_case_days}")

The output is: A Python lambda function checks each day’s reported cases. If the cases are None, the day gets included in the no_case_days list.

Days with no reported cases: ['Tue', 'Thu']
how to check if a Variable is None in Python

This way we can use the lambda function in Python check if a variable is None.

Method 6: Check if the variable is None Python using the isinstance() method

The isinstance() function checks if an object is an instance of a specific type or class. By comparing against type(None), we ascertain if a Python variable’s value is None.

Scenario: An airport in Atlanta wants to ensure flight statuses for multiple flights are updated through Python.

flight_A = None
flight_B = "On Time"
flight_C = ""

if isinstance(flight_A, type(None)):
    print("Status for Flight A not updated.")
if isinstance(flight_B, type(None)):
    print("Status for Flight B not updated.")
if isinstance(flight_C, type(None)):
    print("Status for Flight C not updated.")

The Output is: The system checks if each flight’s status is an instance of None Type. If it is, it indicates the status hasn’t been updated.

Status for Flight A not updated.
how to check None in Python variable

This way we can use the isinstance() method for Variable in Python is None.

Conclusion

This tutorial explains how to check if a variable is None in Python using six different methods such as the is operator, the == operator, the not keyword, the try-except block, the lambda function, or the isinstance() method with some illustrative examples.

Python provides a myriad of ways to check if a variable is None, each with its own use cases and nuances. Whether we’re working with single variables or collections, always ensure what our application requirement is.

You may also like to read: