Python: initialize a multidimensional list

I want to initialize a multidimensional list. Basically, I want a 10x10 grid - a list of 10 lists, each of which contains 10 elements.

Each list value must be initialized with the integer 0.

The obvious way to do this in one layer: myList = [[0]*10]*10 will not work, because it creates a list of 10 links to one list, so changing an item on any line changes it on all lines.

The documentation I saw talks about using [:] to copy a list, but this will not work when using the multiplier: myList = [0]*10; myList = myList[:]*10 myList = [0]*10; myList = myList[:]*10 has the same effect as myList = [[0]*10]*10 .

With the exception of creating the myList.append() s loop, is there an efficient way to initialize the list this way?

+6
source share
4 answers

You can do this quite efficiently with the understanding:

 a = [[0] * number_cols for i in range(number_rows)] 
+14
source

This is a task for ... understanding a nested list!

 [[0 for i in range(10)] for j in range(10)] 
+7
source

I just thought that I would add an answer because the question asked a general n-dimensional case, and I do not think it was answered. You can do this recursively for any number of dimensions in the following example:

 n_dims = [3, 4, 5] empty_list = 0 for n in n_dims: empty_list = [empty_list] * n >>>empty_list >>>[[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]] 
+2
source

In fact, you may need an array instead of some lists. Almost every time I see this "nested list" template, something is not entirely correct.

0
source

Source: https://habr.com/ru/post/949391/


All Articles