Skip to content
Advertisement

How to create a numpy array of lists?

I want to create a numpy array in which each element must be a list, so later I can append new elements to each.

I have looked on google and here on stack overflow already, yet it seems nowhere to be found.

Main issue is that numpy assumes your list must become an array, but that is not what I am looking for.

Advertisement

Answer

As you discovered, np.array tries to create a 2d array when given something like

JavaScript

You have apply some tricks to get around this default behavior.

One is to make the sublists variable in length. It can’t make a 2d array from these, so it resorts to the object array:

JavaScript

And you can then append values to each of those lists:

JavaScript

np.empty also creates an object array:

JavaScript

But you then have to be careful how you change the elements to lists. np.fill is tempting, but has problems:

JavaScript

It turns out that fill puts the same list in all slots, so modifying one modifies all the others. You can get the same problem with a list of lists:

JavaScript

The proper way to initial the empty A is with an iteration, e.g.

JavaScript

It’s a little unclear from the question and comments whether you want to append to the lists, or append lists to the array. I’ve just demonstrated appending to the lists.

There is an np.append function, which new users often misuse. It isn’t a substitute for list append. It is a front end to np.concatenate. It is not an in-place operation; it returns a new array.

Also defining a list to add with it can be tricky:

JavaScript

You need to construct another object array to concatenate to the original, e.g.

JavaScript

In all of this, an array of lists is harder to construct than a list of lists, and no easier, or faster, to manipulate. You have to make it a 2d array of lists to derive some benefit.

JavaScript

You can reshape, transpose, etc an object array, where as creating and manipulating a list of lists of lists gets more complicated.

JavaScript

===

As shown in https://stackoverflow.com/a/57364472/901925, np.frompyfunc is a good tool for creating an array of objects.

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement