How to Fix “TypeError: len() of unsized object”

How to Fix “TypeError: len() of unsized object”

Problem Formulation: How to fix the TypeError: len() of unsized object?

TypeError: len() of unsized object

There are many possible ways why this array may occur. One common pitfall is to use the len() function on a NumPy array with only one value.

Example: Let’s consider the minimal example that creates this error message!

>>> import numpy as np
>>> a = np.array(5)
>>> a
array(5)
>>> len(a)
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    len(a)
TypeError: len() of unsized object
>>> 

Reason why this fails: The array a consists of only one value 5. The fact that the array consists of only one value makes the NumPy array a a scalar—not a container type on which you can call the len() function. You cannot use the len() function with a scalar because scalars are not container types that can have 0 or more elements. Scalars always consist of one element and the len() function is not defined on them!

>>> len(42)
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    len(42)
TypeError: object of type 'int' has no len()

Solution: Instead of relying on the len() function to determine the number of elements in a NumPy array, use the array.size property that is always defined whether it’s a scalar array or not.

Here’s the same example without the TypeError: len() of unsized object:

>>> import numpy as np
>>> a = np.array(5)
>>> a
array(5)
>>> a.size
1

Note: The size property only works for NumPy arrays, not for other types of scalars such as integers or floats. For those, it really doesn’t make any sense to run the len() function on.

Thanks for reading this article, I hope it saved you some time! 🙂