TryBugHunt

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.

PythonPattern: Null and undefined errors

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.

1. Inspect bounds & typesPrint or inspect collection sizes and verify variables are not empty or None/undefined.
2. Guard with safe accessUse optional chaining (?.), dictionary get(), or guard conditions before dereferencing.
3. Trace upstream originsFind where the value was instantiated or returned rather than only patching the symptom.

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

easy

shipping_cost(20) returns None. Big orders correctly get 0.

def shipping_cost(total):
    if total >= 50:
        return 0
    else:
        shipping = 5
Open with hintsRuns in your browser. No account needed.

More 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.