How to Check if a Variable Is Empty or Null (None) in Python

To check if a variable is empty in Python, use if not x:. It is True for None, "", [], {}, set(), (), 0, 0.0 and False. To check for “no value” (what other languages call null), use if x is None:, which is True only for None. Which one you need depends on whether 0 or an empty list is a valid value in your program.

Every example was run with Python 3.12.5, NumPy 2.5.3 and pandas 3.0.6; the output shown is from those runs.

data = []

if not data:
    print("data is empty")

Output:

data is empty

Empty vs. None: which values count?

values = [None, "", [], {}, set(), (), 0, 0.0, False, float("nan"), " ", [0], "0"]

for v in values:
    print(f"{v!r:10} {type(v).__name__:9} not v: {not v!s:5}  v is None: {v is None}")

Output:

None       NoneType  not v: True   v is None: True
''         str       not v: True   v is None: False
[]         list      not v: True   v is None: False
{}         dict      not v: True   v is None: False
set()      set       not v: True   v is None: False
()         tuple     not v: True   v is None: False
0          int       not v: True   v is None: False
0.0        float     not v: True   v is None: False
False      bool      not v: True   v is None: False
nan        float     not v: False  v is None: False
' '        str       not v: False  v is None: False
[0]        list      not v: False  v is None: False
'0'        str       not v: False  v is None: False
Command Prompt screenshot printing not v and v is None for None, empty string, list, dict, set, tuple, 0, 0.0, False, NaN and more in Python
The truth-value test run in the Command Prompt.
Truth table for Python values: which are falsy with not v and which are None, including None, empty string, empty list, dict, set, tuple, 0, 0.0, False, NaN, a space, [0] and '0'
not v is True for every empty or zero value; v is None only for None.

The full rules are in Truth Value Testing in the Python documentation. Three things surprise people: float("nan") is truthy, [0] is not empty (it has one item), and "0" and " " are non-empty strings.

Check if a variable is None (null)

result = None

if result is None:
    print("result has no value (None)")

result = 0
if result is None:
    print("never printed")
if not result:
    print("0 is falsy, but it is NOT None")

Output:

result has no value (None)
0 is falsy, but it is NOT None

Python has no null keyword. None plays that role, and there is exactly one None object, so compare it with is, not ==:

null = None      # Python has no 'null'; None is its equivalent
print(null is None, type(None))
print(null)

Output:

True <class 'NoneType'>
None
value = null

Using null:

NameError: name 'null' is not defined

More examples: check if a variable is None in Python.

Check if a list, dict, set or tuple is empty

items = []
settings = {}
tags = set()
point = ()

for name, value in [("list", items), ("dict", settings), ("set", tags), ("tuple", point)]:
    print(f"{name:5} empty: {not value!s:5}  len: {len(value)}")

Output:

list  empty: True   len: 0
dict  empty: True   len: 0
set   empty: True   len: 0
tuple empty: True   len: 0

if not items: is the usual way; len(items) == 0 says the same thing more explicitly.

Check if a variable is not empty

cart = ["apple"]
email = "ann@example.com"
count = 0

if cart:
    print("cart is not empty")
if email:
    print("email is not empty")
if count is not None:              # 0 is a real value here
    print("count has a value:", count)

Output:

cart is not empty
email is not empty
count has a value: 0

Use if x: for “has content”, but if x is not None: when 0, False or an empty list are real values that you must keep.

Check if a float variable is empty

A float can’t be “empty”. A missing float is usually None or NaN (“not a number”, common in data files), and 0.0 is a real value:

import math

def float_has_value(x):
    """False for None and NaN; 0.0 counts as a real value."""
    return x is not None and not math.isnan(x)

for x in [3.5, 0.0, None, float("nan")]:
    print(f"{x!r:6} not x: {not x!s:5}  has value: {float_has_value(x)}")

Output:

3.5    not x: False  has value: True
0.0    not x: True   has value: True
None   not x: True   has value: False
nan    not x: False  has value: False
Command Prompt screenshot checking whether a Python float variable has a value: 3.5 and 0.0 do, None and NaN do not
Checking floats for None and NaN.

Use math.isnan() to detect NaN. Comparing with == doesn’t work, because NaN isn’t equal to anything, not even itself:

x = float("nan")
print(x == float("nan"), x != x)     # NaN is not equal to anything, even itself

Output:

False True

NumPy arrays and pandas DataFrames

if not arr: doesn’t work for NumPy arrays with more than one element:

import numpy as np

arr = np.array([1, 2, 3])
if not arr:
    print("empty")

Output:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Use .size == 0 for arrays and .empty for pandas objects:

import numpy as np
import pandas as pd

arr = np.array([])
df = pd.DataFrame()
s = pd.Series([], dtype=float)

print("array empty:", arr.size == 0)
print("DataFrame empty:", df.empty)
print("Series empty:", s.empty)

Output:

array empty: True
DataFrame empty: True
Series empty: True

Details: check if a NumPy array is empty.

Check if a variable exists and is not empty

def describe(name, scope):
    if name not in scope:
        return "does not exist"
    value = scope[name]
    if value is None:
        return "exists, but is None"
    if hasattr(value, "__len__") and len(value) == 0:
        return "exists, but is empty"
    return f"exists and has a value: {value!r}"

a = []
b = None
c = "hello"
for name in ["a", "b", "c", "d"]:
    print(name, "->", describe(name, globals()))

Output:

a -> exists, but is empty
b -> exists, but is None
c -> exists and has a value: 'hello'
d -> does not exist

Checking existence by name is rarely needed in normal code (set a default such as None instead); see check if a variable exists in Python.

A reusable is_empty() function

If your data mixes types (for example values read from a form or a file), one function keeps the rules in one place:

import math

def is_empty(value):
    """None, NaN, blank strings and empty containers count as empty. 0 and False do not."""
    if value is None:
        return True
    if isinstance(value, float):
        return math.isnan(value)
    if isinstance(value, str):
        return not value.strip()
    if hasattr(value, "__len__"):
        return len(value) == 0
    return False

for v in [None, "", "  ", [], {}, 0, 0.0, False, float("nan"), [None], "x"]:
    print(f"{v!r:10} -> {is_empty(v)}")

Output:

None       -> True
''         -> True
'  '       -> True
[]         -> True
{}         -> True
0          -> False
0.0        -> False
False      -> False
nan        -> True
[None]     -> False
'x'        -> False
Command Prompt screenshot of a reusable Python is_empty function tested on None, strings, lists, dicts, 0, False and NaN
The reusable is_empty() function in the Command Prompt.

It deliberately treats 0 and False as values, not as empty. Change that rule if your program needs it.

Default values for empty variables

def greet(name=None):
    name = name or "guest"          # replaces None and "" with a default
    return f"Hello, {name}!"

print(greet("Ann"), greet(""), greet(None))

def total(count=None):
    count = 0 if count is None else count   # keeps a real 0
    return count + 1

print(total(0), total(None))

Output:

Hello, Ann! Hello, guest! Hello, guest!
1 1

x or default replaces every falsy value, including 0. Use default if x is None else x to replace only None.

Declare an empty variable

name = ""        # empty string
items = []       # empty list
config = {}      # empty dict
value = None     # "no value yet"
print(repr(name), items, config, value)

Output:

'' [] {} None

Keep going with these related checks:

Frequently asked questions

How do I check if a variable is empty in Python?

if not x: is True for None, empty strings, empty lists, dicts, sets and tuples, and also for 0, 0.0 and False.

How do I check if a variable is null in Python?

Python uses None instead of null: if x is None:. Writing null raises NameError.

What is the difference between not x and x is None?

not x is True for every falsy value (0, “”, [], None…). x is None is True only for None, so 0 and empty lists count as real values.

How do I check if a variable is not empty?

if x: for content, or if x is not None: when 0 or an empty collection is a valid value.

How do I check if a float is empty or NaN?

x is None or math.isnan(x). 0.0 is a real value, and x == float("nan") is always False.

How do I check if a NumPy array or DataFrame is empty?

arr.size == 0 for arrays, df.empty for DataFrames and Series. if not arr: raises ValueError for arrays with several elements.

What is an empty statement in Python?

pass. It does nothing and is used where a statement is required, such as an empty function or if block.