0

I have initialised an empty 2d array as follows:

matrixLength = (len(a)+1)*(len(b)+1)

matrix = []
    step = []

    for i in range(matrixLength):
        matrix.append(step)

when I print it, it gives me this:

[[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]

so far so good. But when I want to iterate over the first Len(a) elements of the 2d array, with the following code:

for i in range(0, len(a)+1):
        print(i)
        matrix[i].append(i)

print (matrix)

instead of getting an array with only the first len(a) elements filled, like this:

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

I get this instead:

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

why?

user3483203
  • 50,081
  • 9
  • 65
  • 94
JustABeginner
  • 321
  • 1
  • 5
  • 14

1 Answers1

1

When you set step to [] you create a reference to one instance of the list type, so when you append matrix with step you put the same reference in all positions. You can easily verify this by printing all matrix element id:

for el in matrix:     
    print(id(el))

You need to create a different list for each element:

matrixLength = (len(a)+1)*(len(b)+1)                   
matrix = []
for i in range(matrixLength):     
     matrix.append(list())

Then you'll be able to update each list independently.

lee-pai-long
  • 2,147
  • 17
  • 18