How to Resolve Python "TypeError: object of type 'NoneType' has no len()"
The TypeError: object of type 'NoneType' has no len()
is a common runtime error in Python. It occurs when you attempt to call the built-in len()
function on a variable that holds the special value None
. The len()
function is designed to return the number of items in a container (like a list, tuple, string, dictionary, or set), but None
, representing the absence of a value, has no length.
This guide explains the common reasons why a variable might hold None
unexpectedly and provides standard solutions to prevent or handle this error.
Understanding the Error: len()
Requires a Container
The built-in len()
function determines the "length" or number of items contained within an object. This only makes sense for objects that are collections or sequences, such as:
list
: Number of elements.tuple
: Number of elements.str
: Number of characters.dict
: Number of key-value pairs.set
: Number of unique elements.
The special None
object represents nothingness; it doesn't contain any items and therefore doesn't have a defined length. Trying to ask for the length of None
results in the TypeError
.
The Cause: Calling len()
on None
The error occurs simply because the variable passed as an argument to the len()
function holds the value None
at the time of the call.
my_variable = None
print(f"Variable type: {type(my_variable)}") # Output: <class 'NoneType'>
# Error Scenario
try:
# ⛔️ TypeError: object of type 'NoneType' has no len()
length = len(my_variable)
print(f"Length: {length}")
except TypeError as e:
print(e)
Common Sources of None
Values
You need to identify why the variable passed to len()
is None
when you expected it to be a list, string, dict, etc.
Explicit Assignment (my_variable = None
)
The variable was directly assigned None
.
Function Returning None
Implicitly (No return
)
A function without an explicit return
statement implicitly returns None
.
def get_data_list():
# Processes data but doesn't return it
processed_data = [1, 2, 3]
print("Processing done.")
# No return statement
result = get_data_list() # result is None
print(f"Function returned: {result}")
try:
print(f"Length: {len(result)}") # ⛔️ Error: len(None)
except TypeError as e:
print(f"Error: {e}")
Output:
ERROR!
Processing done.
Function returned: None
Error: object of type 'NoneType' has no len()
Assignment from Methods Returning None
(e.g., list.sort()
)
Methods modifying objects in-place (like list.sort()
, list.reverse()
, list.append()
) often return None
. Assigning this return value results in a None
variable.
data_list = [5, 2, 8]
# Scenario: Assigning result of sort()
variable_after_sort = data_list.sort() # data_list is sorted, variable_after_sort is None
print(f"Variable after sort: {variable_after_sort}") # Output: None
try:
print(f"Length: {len(variable_after_sort)}") # ⛔️ Error: len(None)
except TypeError as e:
print(f"Error: {e}")
Output:
ERROR!
Variable after sort: None
Error: object of type 'NoneType' has no len()
Function Returning None
Conditionally
A function might return a list/string/etc. only under certain conditions, returning None
otherwise.
def find_items(search_term, items):
matches = [item for item in items if search_term in item]
if matches: # If the matches list is not empty
return matches
# Implicitly returns None if 'matches' list is empty
available_items = ["apple", "banana"]
found = find_items("orange", available_items) # 'orange' not found, function returns None
print(f"Found items: {found}") # Output: None
try:
print(f"Number found: {len(found)}") # ⛔️ Error: len(None)
except TypeError as e:
print(f"Error: {e}")
Output:
ERROR!
Found items: None
Error: object of type 'NoneType' has no len()
Solution 1: Ensure Variable Holds a Sized Container (Fix the Source)
The best fix is usually to correct the logic so the variable reliably holds an object that has a length (list, string, dict, etc.) when len()
is called.
Correct Initialization
Initialize variables expected to be containers with empty versions ([]
, {}
, ""
) instead of None
if they might be used with len()
later.
Ensure Functions Return Sized Objects
Modify functions to always return an object that len()
can process, even if it's an empty one.
# ✅ Fixed function always returns a list
def find_items_safe(search_term, items):
matches = [item for item in items if search_term in item]
# Return the list of matches (which might be empty)
return matches # Returns [] if no matches found
available_items = ["apple", "banana"]
found_safe = find_items_safe("orange", available_items)
print(f"Found items (safe): {found_safe}") # Output: []
# ✅ len() now works correctly on the empty list
print(f"Number found (safe): {len(found_safe)}") # Output: 0
Output:
Found items (safe): []
Number found (safe): 0
Avoid Assigning Results of In-Place Methods
Don't assign the None
result of in-place methods like .sort()
to a variable if you intend to get the length of the modified object later. Use the original variable name.
data_list = [5, 2, 8]
print(f"Original list: {data_list}")
# ✅ Call sort() in-place
data_list.sort()
# ✅ Use len() on the original (now sorted) list variable
print(f"Length after sort: {len(data_list)}")
Output:
Original list: [5, 2, 8]
Length after sort: 3
Solution 2: Check if Variable is None
Before Calling len()
If the variable might legitimately be None
sometimes, check for this case explicitly before calling len()
.
def might_return_none():
import random
return ["data"] if random.choice([True, False]) else None
result_data = might_return_none()
print(f"Function result: {result_data}")
length = 0 # Default length if None
# ✅ Check for None before calling len()
if result_data is not None:
try:
length = len(result_data)
print("Variable is not None.")
except TypeError:
# Should not happen if 'is not None' check ensures it's list/str/etc.
print("Variable is not None but still not measurable?")
length = -1 # Indicate error maybe
else:
print("Variable is None, using default length.")
print(f"Calculated length: {length}")
Output:
Function result: ['data']
Variable is not None.
Calculated length: 1
This prevents the TypeError
by avoiding len(None)
.
Solution 3: Provide a Default Value or Length if None
A common pattern combines the check with providing a default.
def might_return_none():
import random
return ["data", "point"] if random.choice([True, False]) else None
result_data = might_return_none()
print(f"Function result: {result_data}")
# ✅ Get length, providing 0 as default if result_data is None
length = len(result_data) if result_data is not None else 0
# Or slightly shorter: length = len(result_data or [])
# (This uses the fact that 'None or []' evaluates to [])
print(f"Calculated length (with default): {length}")
Output:
Function result: ['data', 'point']
Calculated length (with default): 2
This uses a conditional expression to safely calculate the length or assign 0
if the variable is None
. The result_data or []
trick is a concise alternative but relies on boolean short-circuiting.
How len()
Works (__len__
)
The len()
function works by calling the special __len__()
method of the object passed to it. Objects like lists, strings, dicts, etc., implement __len__()
to return their number of items. NoneType
(the type of None
) does not have a __len__()
method, leading to the TypeError
.
Conclusion
The TypeError: object of type 'NoneType' has no len()
occurs when you call len()
on a variable holding the None
value.
To resolve this:
- Identify the Source: Find out why the variable is
None
instead of the expected list, string, dict, etc. - Fix the Source Logic: The best solution is usually to correct the code (initialize with
[]
/{}
, ensure functions return values, don't assign results of in-place methods) so the variable holds an appropriate container. - Check Before Calling: If the variable might be
None
, useif variable is not None:
before callinglen()
. - Use a Default: Employ conditional logic like
length = len(variable) if variable is not None else 0
orlength = len(variable or [])
to provide a default length (often 0) when the variable isNone
.
Ensure that any object passed to len()
is a valid container or sequence that has a defined length.