3

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I have learnt something new today. Actually, this makes sense since otherwise the operator reshape will not be well defined. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.