Converting a python list into numpy.ndarray recursively

Viewed 462

A weird issue I have encountered today. Would appreciate an explanation for that behavior of np.array:

l1 = np.array([[1], [1]])
type(l1)
Out[43]: numpy.ndarray
l2 = np.array([[1, 2], [1]])
type(l2)
Out[44]: numpy.ndarray

But:

type(l1[0])
Out[45]: numpy.ndarray
type(l2[0])
Out[47]: list

Any ideas?

1 Answers

This behavior is due to the fact that both (or all, to be precise) elements are not in the same dimension.

Consider:

l1 = np.array([[1], [1, 2]])
print(type(l1[0]))
l2 = np.array([[1, 2], [1, 2]])
print(type(l2[0])) 

Will output the (now) expected

<class 'list'>
<class 'numpy.ndarray'>

In order to get numpy.ndarray "all the way down" all elements (and nested elements) must have the same dimension.

Related