Last modified: Dec 04, 2025 By Alexander Williams
Fix TypeError: 'NoneType' has no len() in Python
This error is common for Python beginners. It happens when you call len() on a variable that is None. The len() function requires a sequence or collection.
None is not a sequence. It is a special value representing nothing. This guide will help you understand and fix this error.
Understanding the Error Message
The error message is very direct. "object of type 'NoneType'" means your variable is None. "has no len()" means you tried to get its length.
Python's len() function works on lists, strings, tuples, and dictionaries. It does not work on None, integers, or floats.
This is similar to errors like Fix TypeError: 'int' has no len() in Python. The core issue is the same.
Why Does My Variable Become None?
The most common cause is a function that does not return a value. In Python, a function without a return statement returns None.
You then assign this result to a variable. The variable holds None. Later, you try to use len() on it, causing the crash.
# Example 1: Function returning None
def process_list(my_list):
# This function sorts the list in-place
my_list.sort() # sort() returns None
data = [3, 1, 2]
result = process_list(data) # result is None!
print(len(result)) # TypeError!
Traceback (most recent call last):
File "script.py", line 7, in
print(len(result))
TypeError: object of type 'NoneType' has no len()
Common Scenarios and Fixes
Let's look at specific situations. Each one leads to the same error. We will show the buggy code and the corrected version.
1. Forgetting a Return Statement
You write a function to create or modify data. You forget to return the final object. The caller gets None.
# Buggy Version
def get_user_names(users):
names = []
for user in users:
names.append(user['name'])
# Oops! No return statement
user_list = [{'name': 'Alice'}, {'name': 'Bob'}]
names = get_user_names(user_list) # names is None
if len(names) > 0: # CRASH!
print(names)
The fix is simple. Add a return statement.
# Fixed Version
def get_user_names(users):
names = []
for user in users:
names.append(user['name'])
return names # Now it returns the list
user_list = [{'name': 'Alice'}, {'name': 'Bob'}]
names = get_user_names(user_list) # names is a list
if len(names) > 0: # Works perfectly
print(names)
['Alice', 'Bob']
2. Using List Methods That Return None
Many list methods modify the list in-place. They do not return a new list. They return None. Common methods are sort(), append(), reverse(), and extend().
# Buggy Version
my_list = [5, 2, 8, 1]
sorted_list = my_list.sort() # sort() returns None
print(f"The sorted list has {len(sorted_list)} items") # TypeError!
Do not assign the result of in-place methods. Use the original list after modification.
# Fixed Version
my_list = [5, 2, 8, 1]
my_list.sort() # This sorts my_list itself. Don't assign it.
print(f"The sorted list has {len(my_list)} items") # Use my_list
print(my_list)
The sorted list has 4 items
[1, 2, 5, 8]
3. Conditional Logic That May Not Assign
Your variable might be set inside an if or for loop. If the condition is false, the variable never gets a proper value. It remains None.
# Buggy Version
def find_long_name(names):
result = None # Default to None
for name in names:
if len(name) > 10:
result = name
# What if no name is longer than 10? result stays None.
return result
name_list = ["Tom", "Jane", "Max"]
long_name = find_long_name(name_list) # Could be None
print(len(long_name)) # TypeError if long_name is None!
Always handle the None case. Check before using len().
# Fixed Version
def find_long_name(names):
result = None
for name in names:
if len(name) > 10:
result = name
return result
name_list = ["Tom", "Jane", "Max"]
long_name = find_long_name(name_list)
# Check for None first
if long_name is not None:
print(f"Found: {long_name}, length: {len(long_name)}")
else:
print("No long name found.")
No long name found.
General Debugging Strategy
Follow these steps when you see this error.
First, find the line where the error occurs. Look at the traceback. It tells you the file and line number.
Second, identify the variable passed to len(). Print its type and value just before the error line.
# Debugging Example
variable = some_function()
print(f"Type: {type(variable)}, Value: {variable}") # Debug print
length = len(variable) # Error line
If the type is NoneType, trace back. Where did this variable come from? Was it returned from a function? Was it assigned in a conditional block?
Third, ensure the source provides a valid sequence. Fix the function to return a value. Or check conditions to ensure assignment.
Prevention with Defensive Programming
You can write code that avoids this error. Use defensive programming.
Use type hints to clarify what a function returns. This helps you think about the return value.
Always initialize variables with a sensible default. Use an empty list [] instead of None when possible.
# Better practice: Return an empty list
def get_data():
# ... some logic that might fail
if condition:
return ["data1", "data2"]
else:
return [] # Return empty list, not None
data = get_data()
# Now this is always safe:
print(f"Got {len(data)} items.")
Use isinstance() checks if you are unsure of a variable's type. This can prevent many type-related errors, similar to issues like Fix TypeError: isinstance() arg 2 Must Be Type.
def safe_get_length(item):
if item is None:
return 0
elif isinstance(item, (list, str, tuple, dict)):
return len(item)
else:
raise TypeError(f"Unsupported type for len(): {type(item)}")
Conclusion
The "NoneType has no len()" error is a classic Python mistake. It stems from calling len() on a None value.
The root cause is usually a missing return statement or using an in-place method's result.
To fix it, trace the variable back to its source. Ensure functions return actual data. Check for None before calling len().
Adopt defensive habits. Return empty collections instead of None. Your code will be more robust. You will spend less time debugging simple errors.
Understanding this error deepens your grasp of Python's type system. It helps you avoid related issues like Fix TypeError: List Indices Must Be Integers.