0

I have a 10 by 10 matrix which has dic as element. When I only want to update a single value, it ends up updating all values in that column. Why? and How to fix it?

m = [[{}] * 10]*10

m[0][0] = {"a":1}

enter image description here

Is there an equivalent numpy style to do the same thing(if it could be quicker by using Numpy)?

Franva
  • 6,565
  • 23
  • 79
  • 144
  • You have a list of 10 references to one sublist, which is in turn a list of 10 references to one dict. If you did `m[1][1]['a'] = 1` you'd see that reflected across all 100 nested elements. – Samwise Apr 13 '23 at 14:36
  • An easy fix is to define `m` like: `m = [[{} for _ in range(10)] for _ in range(10)]` – Samwise Apr 13 '23 at 14:39
  • thanks @Samwise I just saw the reason and wonder why the 2nd 10 ([[{}] * 10]* **10**) makes the reference whereas the 1st 10 creates new variables?? – Franva Apr 13 '23 at 14:40
  • It doesn't, but your `m[0][0] = {"a":1}` rebinds one of those references, which "fixes" the problem in that one spot. – Samwise Apr 13 '23 at 14:41
  • @Samwise I tried this code `[[{}] * 10 for _ in range(10)]` and it also works. – Franva Apr 13 '23 at 14:42
  • It doesn't, not completely. You should try the `m[1][1]['a'] = 1` that I suggested, since that will demonstrate both dimensions of the problem. – Samwise Apr 13 '23 at 14:43
  • I tried, it does changed more than 1 element values, but it only affects the 1st row. I am really confused. Do we have a way to use numpy to create a 10 by 10 dict type 2D array? – Franva Apr 13 '23 at 14:46
  • thanks @Samwise I decided to use the code you suggested as it works well. – Franva Apr 13 '23 at 14:59
  • Hi @Samwise , do you want to post your code as the answer? – Franva Apr 20 '23 at 13:46
  • The linked dupe already covers it. :) – Samwise Apr 20 '23 at 14:14

0 Answers0