1

I need to assign a predefined dimension to a list of lists. This is because the code within the for loop is using references to an 'existing' array of such dimension and it would throw an 'index out of range' error if the list is not preloaded before entering the loop.

The following slice of code intended to do such task does not produce the result I would expect.

a, b = 2, 3

matrix = [[[None]*2]*a]*b

for i in range(b):
    for j in range(a):
        print(i, j)
        matrix[i][j] = [i, j]
print(matrix)

I am expecting the elements of the two-dimension list of lists to be a two-elements list. Such as the print statement shows in the following output:

0 0
0 1
1 0
1 1
2 0
2 1
[[[2, 0], [2, 1]], [[2, 0], [2, 1]], [[2, 0], [2, 1]]]

The list of lists should contain the pairs printed.

Alejandro QA
  • 334
  • 4
  • 9
  • 2
    related/(dupe?): https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly – Ch3steR Feb 04 '22 at 13:55
  • 1
    Thank you very much @Ch3steR, I did indeed look for the answer to this for several hours before posting the question. – Alejandro QA Feb 04 '22 at 13:59
  • 2
    Don't use list multiplication, ever. Then you don't have to worry about the difference between a list of mutable values and a list of immutable values. – chepner Feb 04 '22 at 14:00
  • 2
    using list multiplication on another list will create multiple references to the same list object, so for example matrix[0][1] references the same list object as matrix[0][0]. Therefore, updating matrix[0][1] also updates matrix[0][0] (and everywhere else that it is referenced in matrix) – Trevor Pogue Feb 04 '22 at 14:10
  • 1
    `[[[None for _ in range(2)] for _ in range(a)]for _ in range(b)]` – dawg Feb 04 '22 at 14:24

1 Answers1

1

The correct way to pre-dimension the list of lists is as follows:

a, b = 2, 3

matrix = [[[None for _ in range(2)]  
                 for _ in range(a)]  
                 for _ in range(b)] 

for i in range(b):
    for j in range(a):
        print(i, j)
        matrix[i][j] = [i, j]
print(matrix)

So the output is as expected:

0 0
0 1
1 0
1 1
2 0
2 1
[[[0, 0], [0, 1]], [[1, 0], [1, 1]], [[2, 0], [2, 1]]]
Alejandro QA
  • 334
  • 4
  • 9