TypeError: object of type ‘NoneType’ has no len()

The python error TypeError: object of type ‘NoneType’ has no len() occurs while attempting to find the length of an object that returns ‘None’. The python object whose data type is NoneType can’t be used in length function. The Length function is used for data structures that store multiple objects.

The python variables, which have no value initialised, have no data type. These variables are not assigned any value, or objects. The length function can not be called the variables which are not allocated with any value or object. If you call the length function for these variables of none type, it will throw the error TypeError: object of type ‘NoneType’ has no len()



Exception

The error TypeError: object of type ‘NoneType’ has no len() will display the stack trace as below

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 2, in <module>
    print (len(s))
TypeError: object of type 'NoneType' has no len()
[Finished in 0.1s with exit code 1]


How to reproduce this error

If a python variable is not assigned with any value, or objects, the variable would have none data type. If the length function is invoked for the none type variable, the error TypeError: object of type ‘NoneType’ has no len() will be thrown.

test.py

s=None
print (len(s))

Output

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 2, in <module>
    print (len(s))
TypeError: object of type 'NoneType' has no len()
[Finished in 0.1s with exit code 1]


Solution 1

The python variable which is not assigned with any value or object, should be assigned with a value or object. If the variable is not assigned with any value or object , assign with an object such as list, tuple, set, dictionary etc.

s=[1,2]
print (len(s))

Output

2
[Finished in 0.0s]


Solution 2

Due to the dynamic creation of the variable the python variable may not be assigned with values. The datatype of the variable is unknown. In this case, the None data type must be checked before the length function is called.

s=None
print type(s)
if s is None : 
	print "Value is None"
else:
	print (len(s))

Output

Value is None


Solution 3

The python variable should be validated for the expected data type. If the variable has the expected data type, then the length function should be invoked. Otherwise, the alternate flow will be invoked.

s=None
print type(s)
if type(s) in (list,tuple,dict, str): 
	print (len(s))
else:
	print "not a list"

Output

not a list


Solution 4

If the data type of the variable is unknown, the length function will be invoked with try and except block. The try block will execute if the python variable contains value or object. Otherwise, the except block will handle the error.

s=None
try :
	print (len(s))
except :
	print "Not a list"

Output

Not a list
[Finished in 0.0s]



Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *