Python TypeError: Object of Type 'NoneType' Has No Len()

Python TypeError: Object of Type 'NoneType' Has No Len()

  1. the TypeError: object of type 'NoneType' has no len() in Python
  2. Solve the TypeError: object of type 'NoneType' has no len() in Python

In this article, we’ll discuss solving the TypeError object of type NoneType has no en() in Python.

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

As we know, the None has no length. So, we cannot find its length with the len() function because len() does not support None data types.

If you try to find the length a none with the len() it will throw the TypeError: object of type 'NoneType' has no len(). Let’s understand it through an example.

Code:

# initializing none to val
val = None

# display the data type of val
print(type(val))

# display the length of val
print(len(val))

Output:

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

In the above code, the variable val whose value is None belongs to the NoneType class, and if you try to find the length of val, it will give a TypeError: object of type 'NoneType' has no len(). This means that NoneType has no length.

Solve the TypeError: object of type 'NoneType' has no len() in Python

So far, we have learned about what the TypeError: object of type 'NoneType' has no len() and why it occurs. It is important to know that the len() function causes this error because it does not support the None type to find its length.

If you see the attributes of None, the len is missing there, which means you cannot find the length of None. To verify it, run the code below.

Code:

print('__len__' in dir(None))

Output:

False

The above line of code checks __len__ in the attributes of None, and it has returned False, which means __len__ isn’t available in the attributes of None. On the other hand, as we mentioned, you can find the length of any collection like array, list, string, etc.

Code:

print('__len__' in dir(list))

Output:

True

It has returned True because we can find the length of any collection; in this case, it is the list.

To solve the TypeError: object of type 'NoneType' has no len() you need to pass collection or strings to the len() function instead of individual values or None.

Zeeshan Afridi avatar Zeeshan Afridi avatar

Zeeshan is a detail oriented software engineer that helps companies and individuals make their lives and easier with software solutions.

LinkedIn

Related Article - Python Error

  • Python PermissionError: [WinError 5] Access Is Denied
  • Python TypeError: 'DataFrame' Object Is Not Callable
  • Python TypeError: Can't Convert 'List' Object to STR
  • Local Variable Referenced Before Assignment Error in Python
  • Python Handling Socket.Error: [Errno 104] Connection Reset by Peer
  • Python Is Not Recognized in Windows 10