TypeError: object of type 'NoneType' has no len()
In this article, we will learn about the error “TypeError: object of type 'NoneType' has no len( )”
This error is generated in Python when we try to calculate the length of an object which returns ‘none’.
Let us understand it more with the help of an example.
Example:
# Creating a list MyList
MyList = [324,324,126,12,4]
# Assigning sorted list to 'x'
x=MyList.sort()
# Calculating length of the sorted list
print(len(x))
# Print MyList
print(MyList)
Output:
File "list.py", line 8, in <module>
print(len(x))
TypeError: object of type 'NoneType' has no len()
In the above example in line 8 of the code we are calculating the length of the sorted list. But we know sort( ) method returns 'none'. So instead of calculating the length of the list, we are calculating the length of 'none'. thus the error
TypeError: object of type 'NoneType' has no len( ) is encountered.
Also, x=MyList.sort( ) doesn’t make any sense. Since the sort( ) method doesn’t return anything and we are assigning 'none' to 'x'.