TypeError: object of type 'NoneType' has no len()
TypeError: object of type 'NoneType' has no len() in Python means you called len() on a value that is None. Usually a function forgot to return its result, or a lookup returned None when nothing was found.
How do I fix TypeError: object of type 'NoneType' has no len()?
To fix TypeError: object of type 'NoneType' has no len() in Python, locate the line causing the error and check the values right before it runs. Most occurrences happen because of a function has no return statement. Apply a defensive check or safe fallback, make sure collections or objects exist before access, and verify return values from upstream functions.
What does TypeError: object of type 'NoneType' has no len() mean?
len() requires a sequence or container (such as a string, list, dictionary, or tuple). None represents the absence of a value and does not define a length. This error means your code assumed a valid list or string was present, but got None instead.
Why does TypeError: object of type 'NoneType' has no len() happen?
1. A function has no return statement
Functions without an explicit return statement implicitly return None.
Breaks
def get_items():
items = [1, 2, 3]
count = len(get_items())Works
def get_items():
items = [1, 2, 3]
return items
count = len(get_items())2. Calling len() on a mutating method's return value
list.sort(), list.append(), and list.reverse() modify the list in place and return None.
Breaks
count = len(items.sort())Works
items.sort()
count = len(items)3. dict.get() or regex match returned None
When a key is missing or pattern does not match, the result is None.
Breaks
tags = user.get("tags")
num_tags = len(tags)Works
tags = user.get("tags", [])
num_tags = len(tags)How to find it in your own code
Provide a fallback value (e.g. `user.get("tags", [])` or `val = result or ""`) before calling len(), or check `if value is not None:` first.
Try it: fix this bug
easyshipping_cost(20) returns None. Big orders correctly get 0.
def shipping_cost(total):
if total >= 50:
return 0
else:
shipping = 5More challenges with this error
Each of these challenges runs into this error or pattern. Find the bug and fix it in your browser โ no install, no account needed.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.