0

I have made a 5x5 python list (A) and a numpy array (B). But when I set A[0][0]=1 for the python 2D list and set B[0][0]=1 for the numpy array, I get these results (I was expecting to get results like I got for the numpy array, but why is it converting all the first elements of all the rows into 1 for the python list?):

A = [[0] * 5] * 5
A[0][0] = 1
print(A)

B = np.zeros((5, 5))
B[0][0] = 1
print(B)

results:
A= [[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]]
B= 
[[1. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]]
Nakkhatra
  • 83
  • 10
  • 1
    See here for details: [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – sj95126 Sep 13 '21 at 23:13

1 Answers1

0

This happens because of how you initialise the variable A.

A = [[0] * 5] * 5

[0] * 5 creates 5 different pointers but the outer * 5 copies those pointers to a different location rather than creating new ones. Therefore, when you modify one of the copies of those five pointers, that change gets reflected to the other sublists since they contain references to the original five pointers.

The correct way to achieve your behavior is:

A = [0 for _ in range(5)] * 5
Rayan Hatout
  • 640
  • 5
  • 22