-2

I would like to create in python a list that inside has 3 lists, each of them have 2 vectors of 4 elements, something like that:

[[[0,0,0,0],[0,0,0,0]], 
 [[0,0,0,0],[0,0,0,0]], 
 [[0,0,0,0],[0,0,0,0]]]

This is just a simple example but I would like to automate it in order to be able to create an object like that with a much higher number of elements.

I tried to do it the following way:

grid=[np.zeros((2,4)) for x in range(3)]
grid

However when I print it the result is something like this instead

[array([[0., 0., 0., 0.],
        [0., 0., 0., 0.]]), array([[0., 0., 0., 0.],
        [0., 0., 0., 0.]]), array([[0., 0., 0., 0.],
        [0., 0., 0., 0.]])]

The structure should be fine, but I don´t know if the fact that it says array is normal or I did something wrong.

Thanks in advance for your help

AMC
  • 2,642
  • 7
  • 13
  • 35
pablo11prade
  • 93
  • 1
  • 1
  • 6
  • 2
    What is the problem so ? – azro Mar 21 '20 at 18:05
  • this is a list of `np.array` not list of lists; they behave similarly and depending on what you want to do, it might be the correct approach. You can see some of the differences in terms of memory allocation [here](https://webcourses.ucf.edu/courses/1249560/pages/python-lists-vs-numpy-arrays-what-is-the-difference) – nickyfot Mar 21 '20 at 18:09
  • 1
    Confused: If you are already using numpy for your project, and you want to create this kind of "rectangular" structure where everything is the same size at a given level of nesting... then why do you want to produce a list of lists (of lists...) instead of a numpy array? – Karl Knechtel Mar 21 '20 at 18:54
  • Why not `np.zeros((3,2,4), int)`? Add `tolist()` to make a list of lists of lists. – hpaulj Mar 21 '20 at 19:14
  • I'm voting to close this. It's pretty basic, it's all over the place, and I can't see it ever being useful to future readers. – AMC Mar 21 '20 at 19:31

1 Answers1

1

You have here a list of 2D np.array, if you want a list of list of lists :

grid = [[[0 for _ in range(4)] for _ in range(2)] for _ in range(3)]

The following will build the same structure, but each sublist will be copy, so unusable (see List of lists changes reflected )

grid = [[[0] * 4] * 2] * 3
azro
  • 53,056
  • 7
  • 34
  • 70