6

I'm trying to create a numpy array that looks like

array([[list([]), list([])],
       [list([]), list([])],
       [list([]), list([])]], dtype=object)

This array has shape (3,2). However, whenever I do

np.array([[list(), list()], [list(), list()], [list(), list()]])

I end up getting

array([], shape=(3, 2, 0), dtype=float64)

How do I solve this?

4
  • 1
    Perhaps stackoverflow.com/questions/33983053/… Commented Aug 5, 2019 at 18:29
  • 2
    Why do you need such a structure? Commented Aug 5, 2019 at 18:48
  • It is very likely that you do not want a numpy array of lists. Commented Aug 5, 2019 at 20:10
  • np.array tries to create multidimensional numeric (or string) array, which it can do if all the input lists have a consistent size. It's only when the sizes differ that it falls back on creating an object dtype array (or in some cases raising an error). Commented Aug 5, 2019 at 20:17

1 Answer 1

9

You could use the following:

np.frompyfunc(list, 0, 1)(np.empty((3,2), dtype=object))  

We first turn list into a ufunc that takes no arguments and returns a single empty list, then apply it to an empty 3x2 array of object type.

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

1 Comment

I've recommended frompyfunc as a way of filling an array with custom class instances. This is a nice use of the idea with standard types like list.

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.