2

I just started programming with Python and I have a question concerning 2D arrays. I need to create a matrix (numpy forbidden) of a certain size from av[1] and save it so that I can multiply it with another one later on. The logical thing for me was: 1- Get the length of av[1]; 2- Transform the av[1][] to it's ASCII equivalent with ord and finally 3- Insert that value into a list called key_matrix.

The matrix needs to be the smallest size possible and in a "square form", so I calculate the smallest square containing the len of av[1] ( called matrix_size ) and then I initialize my array like this:

key_matrix = [[0] * matrix_size] * matrix_size; 

Like that I get my square matrix filled with 0. If matrix_size = 3 for example I get:

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

Now the strange part is (and also the part that I'm stuck on) the following, I use

index1 = 0;
index2 = 0;
key_matrix[index1][index2] = ord(sys.argv[1][0]);
print(key_matrix);

to fill only the 1st element of the 1st line.

While the result should be:

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

I get:

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

Me and my friends really cant seem to figure out the reason why it does this, any help is welcome!

Thank you all for reading :)

  • Indeed it does, thank you! As I'm still somewhat new I didn't know the exact thing to look for but this answers a lof of my questions, I just need to change the way that I declare my key_matrix. – SlavicPavlovic Dec 12 '19 at 16:30
  • Not to worry; it's a very common and very understandable mistake. – kaya3 Dec 12 '19 at 16:32

1 Answers1

3

The memory address of the lists are the same when you write [[0] * matrix_size] * matrix_size, it basically reuses the memory address of the first [0] * matrix_size array as the same reference for multiple times for other lists. Since these lists are not independent from memory address perspective, we would have issue modifing only one of the list. You can do below as a quick fix for the issue:

>>> key_matrix2 = [[0] *3 for i in range(matrix_size)]
>>> key_matrix2
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> key_matrix2[0][1] = 2
>>> key_matrix2
[[0, 2, 0], [0, 0, 0], [0, 0, 0]]
Paul Lo
  • 6,032
  • 6
  • 31
  • 36