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
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! 🙂
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.