When working with Python, you will likely encounter the error “TypeError: object of type ‘NoneType’ has no len()”. Let’s learn about the cause of this error as well as its solution through this article. Keep reading for detailed information.
What causes this error?
You will get the error message: “TypeError: object of type ‘NoneType’ has no len()” in Python when you try to pass in the len() function a value ‘None’.
The len() function in Python takes a single parameter – a collection or a sequence – and returns the length of that object.
Syntax:
len(object)
Where: object – Required parameter. An object. It must be a collection or a sequence.
Therefore, if you pass in the len() function a value of ‘None’, the error is obvious.
Here is an example of how this error occurs:
def getMessage(): print("Welcome to the LearnShareIT community.") # None value message = getMessage() print(len(message))
Error:
TypeError: object of type 'NoneType' has no len()
Since the getMessage() function does not return any value, the ‘message’ variable gets a value of ‘None’.
Solved – TypeError: object of type ‘NoneType’ has no len() in Python
To work around this problem, ensure that the value you pass to len() is different from ‘None’.
As in the above example, we can use the return statement to get a value from the function.
def getMessage(): return "Welcome to the LearnShareIT community." message = getMessage() print(len(message))
Output:
38
Alternatively, you can also use the conditional statement to check if a variable is storing a ‘None’ value before passing it into the len() function.
message = None # Use the if/else block if message != None: print(len(message)) else: print("The variable is storing a 'None' value")
Output:
The variable is storing a 'None' value
At this point, you no longer have to worry about the error because the conditional statement prevents getting the length of a variable that stores a ‘None’ value.
Or you can also directly print the variable to be checked to see its value with the print() statement.
noneMessage = None message = "Welcome to the LearnShareIT community." print(noneMessage) print(message)
Output:
None
Welcome to the LearnShareIT community.
Summary
In summary, we have just shared with you the necessary information about the “TypeError: object of type ‘NoneType’ has no len()” in Python. To overcome this error, you need to check the value of the variable passed in the len() function and make sure it is different from a ‘None’ value. That’s the end of this post. Hopefully, the information we conveyed will be helpful to you.

My name’s Christopher Gonzalez. I graduated from HUST two years ago, and my major is IT. So I’m here to assist you in learning programming languages. If you have any questions about Python, JavaScript, TypeScript, Node.js, React.js, let’s contact me. I will back you up.
Name of the university: HUST
Major: IT
Programming Languages: Python, JavaScript, TypeScript, Node.js, React.js