. Advertisement .
..3..
. Advertisement .
..4..
I encounter the error ”typeerror: len() of unsized object” when I run my code:
>>> 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
>>>
Can someone give me some solutions for this issue?
The cause: This error happens because there is only one value (5s) in the array
a
. The NumPy arraya
is a scalar and cannot be used as a container type for thelen()
function because it only contains one value. Because scalars are not container types that can store 0 or more elements, you cannot use thelen()
function with them. Scalars never have more than one element and don’t have the len()
method declared on them.Solution: You can use the
array.size
property which is always defined whether it’s a scalar array or not instead of relying on thelen()
function to determine the number of elements in a NumPy array: