0

I have a list of numpy arrays e.g.

>>> list_of_mats = [np.array([[1, 2, 3],
                              [4, 5, 6]])]*2

>>> print(list_of_mats[0])
[[1 2 3]
 [4 5 6]]

>>> print(list_of_mats[1])
[[1 2 3]
 [4 5 6]]

Now, I want to modify the first row - first column element in the first numpy array (matrix), so I did something like this:

>>> list_of_mats[0][0, 0] = 7

But, it's modifying the first element in both arrays:

>>> print(list_of_mats[0])
[[7 2 3]
 [4 5 6]]

>>> print(list_of_mats[1])
[[7 2 3]
 [4 5 6]]

So, how can I modify only one numpy array in the list of numpy arrays?

Milan
  • 1,743
  • 2
  • 13
  • 36
  • This one's come up so many times but can I remember where to find the duplicate question...? – alani Aug 27 '20 at 17:44
  • @alani Sorry if this question already exists. I tried finding the answer on SO, but didn't find what I have been looking for. – Milan Aug 27 '20 at 17:47
  • Okay, this looks like a slight variant on a question that has come up lots of times. The bottom line is that `[some_expression] * 2` will create a list of two references to the same object, and what you need instead is `[some_expression for _ in range(2)]` – alani Aug 27 '20 at 17:48
  • And don't be tempted to put the `some_expression` into another variable or you'll end up with the same problem. Actually do `[np.array([[1, 2, 3], [4, 5, 6]]) for _ in range(2)]` -- though you could probably put the inner list `[[1,2,3],[4,5,6]]` bit in another variable but make sure that the `np.array(...)` actually appears as such inside the list comprehension. – alani Aug 27 '20 at 17:50
  • 1
    I replaced`list_of_mats = [np.array([[1, 2, 3], [4, 5, 6]])]*2` with `list_of_mats = [np.array([[1, 2, 3], [4, 5, 6]]) for _ in range(2)]` and it worked. Thank you! – Milan Aug 27 '20 at 18:08

0 Answers0