python type_error ai_generated true

TypeError: object of type 'NoneType' has no len()

ID: python/typeerror-no-len

Also available as: JSON · Markdown
95%Fix Rate
95%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
311 active

Root Cause

Calling len() on an object that doesn't support it. Usually None from a function that returns nothing.

generic

Workarounds

  1. 95% success The variable is probably None — check function that assigns it (many list methods return None)
    # Bad: my_list = my_list.sort()  # .sort() returns None!
    # Good: my_list.sort()  # sorts in place

    Sources: https://docs.python.org/3/library/stdtypes.html#list.sort

  2. 88% success Add None check before calling len(): if obj is not None: len(obj)
    if obj is not None: len(obj)

    Sources: https://docs.python.org/3/library/functions.html#len

Dead Ends

Common approaches that don't work:

  1. Add __len__ to the class 70% fail

    Usually the variable is wrong type, not missing __len__

  2. Check if len() > 0 with try/except 75% fail

    Hides the root cause — variable shouldn't be None

Error Chain

Frequently confused with: