Python Check If Variable Is Empty

In this tutorial, I will show you how to check if a variable is empty in Python. Handling empty variables is one of the most common tasks I perform in my daily coding routine. If you don’t handle empty data structures correctly, your application will likely crash or produce unexpected errors.

Coming from a background where I spent over a decade building complex React applications, I learned that validating data state is crucial. Python handles “emptiness” a bit differently than JavaScript, but it offers very clean and readable ways to do it.

In this guide, I will cover various methods to check for empty strings, lists, dictionaries, and even None types

Method 1: Use the len() Function in Python

Sometimes, explicit is better than implicit. If you want to be sure you are dealing with a sequence (like a string or a list) and not just a None value, using len() is a safe bet.

For example, let’s say we are validating a US Zip Code input field.

zip_code_input = ""

# Explicitly checking the length
if len(zip_code_input) == 0:
    print("Error: Zip Code field cannot be empty.")
else:
    print("Zip Code received.")

You can see the output in the screenshot below.

len in python

If the variable zip_code_input happens to be None instead of a string instead, this code will throw a TypeError. Use this method when you are certain the variable is an initialized sequence.

Method 2: Compare Directly to an Empty Value

You can compare your variable directly against what an empty version of that variable looks like. If you have a list, you compare it to []. If you have a string, you compare it to “”.

Here is an example involving a shopping cart for an American e-commerce site.

shopping_cart = []
discount_code = ""

# Checking against an empty list literal
if shopping_cart == []:
    print("Your cart is empty. Add some items!")

# Checking against an empty string literal
if discount_code == "":
    print("No discount code applied.")

You can see the output in the screenshot below.

how to make a empty variable in python

While this is easy to read, it is slightly less efficient than the “Pythonic” way I mentioned first. However, it effectively communicates intent if you want to strictly check for a specific type of emptiness.

Method 3: Check for None (The Null Check)

In strictly typed languages or when working with APIs, receiving a null (or None in Python) is different from receiving an empty list.

None usually means “no value exists” or “initialization failed,” whereas an empty list means “the value exists, but it has no contents.”

user_ssn = None

# Check if the variable is explicitly None
if user_ssn is None:
    print("System Error: User SSN data was never loaded.")
elif user_ssn == "":
    print("Data Error: SSN field is blank.")
else:
    print("SSN Found.")

You can see the output in the screenshot below.

check if set is empty python

Notice I used is None rather than == None. In Python, is checks for identity, which is faster and safer for singletons like None.

Method 4: Handle Whitespace with .strip()

This is a scenario I encountered constantly when building frontend forms in React, and the backend logic in Python is just as important. A user might press the spacebar five times in a “Name” field.

Technically, that string is not empty (it has a length of 5), but for our application logic, it contains no data. To handle this, we use the .strip() method.

# User entered spaces in the City field
city_input = "   "

# Without strip, this would look 'full'
if not city_input.strip():
    print("Error: Please enter a valid US City.")
else:
    print(f"Shipping to {city_input}.")

You can see the output in the screenshot below.

len function python

This is the robust way to validate text inputs.

Method 5: Check Pandas DataFrames

The standard Python checks (if not variable) can sometimes be ambiguous or throw errors when applied to a DataFrame or Series.

Pandas provides a specific attribute called .empty to handle this.

import pandas as pd

# Creating an empty DataFrame mimicking a CSV load
ca_housing_data = pd.DataFrame()

if ca_housing_data.empty:
    print("The dataset is empty. Check your CSV file path.")
else:
    print("Data loaded successfully.")

Never use if ca_housing_data: directly, as Pandas will raise a ValueError stating the truth value of a DataFrame is ambiguous. Always use the .empty attribute.

Method 6: Use try and except for Uninitialized Variables

Occasionally, you might need to check if a variable exists at all. If you try to access a variable that hasn’t been defined, Python raises a NameError.

While it is a better practice to initialize your variables, sometimes you are working with legacy code where this isn’t guaranteed.

You can catch this error to handle the “empty” or “non-existent” state.

try:
    # Attempting to print a variable that hasn't been defined yet
    print(f"The current President is {current_president}")
except NameError:
    print("The variable 'current_president' is not defined (effectively empty).")

I rarely recommend relying on this for flow control, but it is a useful safety net.

Method 7: Check Any() or All()

Sometimes “empty” is subjective. You might have a list of values where None or 0 counts as empty, and you want to see if any valid data exists.

For example, imagine a voting record where 0 means no vote was cast.

Python

# Votes from 5 districts (0 indicates no turnout)
district_votes = [0, 0, 0, 0, 0]

# any() returns True if at least one element is Truthy
if not any(district_votes):
    print("Alert: No votes recorded in any district.")
else:
    print("Votes are present.")

This is a powerful, functional approach to checking the contents of a collection rather than just the collection itself.

Which Method Should You Choose?

I have shown you several ways to check for empty variables, and you might be wondering which one is best.

Based on my experience, here is a quick rule of thumb:

  1. General Use: Use if not variable:. It handles strings, lists, dicts, and None automatically.
  2. User Input: Use if not variable.strip(): to catch “invisible” whitespace.
  3. Data Science: Use df.empty for Pandas DataFrames.
  4. Strict Typing: Use if variable is None: if you need to differentiate between an empty list and a missing list.

Choosing the right method makes your code cleaner and easier to debug later.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.