2

Can someone tell me why a works while b does not with ValueError: setting an array element with a sequence? This says the "multi-dimensional" reason, but in my case, I think a and b are the same.

import numpy as np

a=np.array([[1],2,3])
b=np.array([1,2,[3]])
lanselibai
  • 1,203
  • 2
  • 19
  • 35
  • Making an array from lists with mixed nesting is tricky. `np.array` first tries to make a regular multidimensional array. It fails for both `a` and `b`, so has to fall back on ad hoc alternatives. – hpaulj Mar 29 '18 at 15:39

1 Answers1

4

Numpy is observing the first element to see what dtype the array is going to have. For a it sees a list and therefore produces an object array. It happily moves on to fill in the rest of the elements into the object array. For b, it sees a numeric value and assumes it's going to be some numeric dtype. Then it borks when it gets to a list.

You can override this by stating object dtype in the first place

a=np.array([[1],2,3])
b=np.array([1,2,[3]], 'object')

print(a, b, sep='\n\n')

[list([1]) 2 3]

[1 2 list([3])]

Mind you, that may not be exactly how Numpy is identifying dtype but it's got to be pretty close.

piRSquared
  • 285,575
  • 57
  • 475
  • 624
  • So `list([1])` means it is only a `list`, not a `numpy list`? – lanselibai Mar 29 '18 at 15:26
  • 1
    _For a it sees a list and therefore produces an object array._ It really can't be that simple since for example `[[1], [2], [3]]` looks exactly the same in the first position. – Paul Panzer Mar 29 '18 at 15:26
  • @PaulPanzer you are right of course. But it's the simplest way to get the point across. Numpy is doing some checking. Those checks fail to make the correct guess for `b = np.array([1, 2, [3]])` – piRSquared Mar 29 '18 at 15:27