0

I'm trying to edit a value in a 2D array.

Just the value at [0][0] but when I edit it, it propagates to all the values at [x][0] and I don't understand why.

I then copied the exact line from an example that I found online and it works but I don't understand what the difference is.

I simplified both examples and they still don't have the same solutions. This doesn't add up.

counter= 3*[4*[0]]
counter[0][3] = 7
print(counter)

T = [[0, 0, 0, 0], [0, 0,0,0], [0, 0, 0, 0]]
T[0][3] = 7
print(T)

the top print statement gives: [[0, 0, 0, 7], [0, 0, 0, 7], [0, 0, 0, 7]]

the bottom gives: [[0, 0, 0, 7], [0, 0, 0, 0], [0, 0, 0, 0]]

but they should be the same.

ParthS007
  • 2,581
  • 1
  • 22
  • 37
David Raji
  • 16
  • 2
  • You haven't said what `counter` is, so how can anyone answer? – Denziloe Jun 09 '19 at 00:24
  • Please provide the value of Counter. – ParthS007 Jun 09 '19 at 00:24
  • More [here](https://stackoverflow.com/questions/18946728/changing-an-element-in-one-list-changes-multiple-lists) and [here](https://stackoverflow.com/questions/2739552/2d-list-has-weird-behavor-when-trying-to-modify-a-single-value) and above all, [this](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – Sheldore Jun 09 '19 at 00:25
  • It's quite obvious what is going on without even knowing how `counter` has been defined. 'counter' is likely a 'list of lists', but it's not a list of unique lists but rather a list of multiple pointers to the same embedded list. So when you change that one embedded list with a reference pulled from one element of the outer list, you'll see that same change when you reference that same sub-list with any of the other references in the outer list. In your second example, you have created a list of lists where each embedded list is truly unique, and so changing one does not change the others. – CryptoFool Jun 09 '19 at 00:33

0 Answers0