1

I wrote ans = [[0,0],[0,0]]. Then ans[0][0] is 0. But me writing ans[0][0] += 1, it was changed to [[1,0],[1,0]]. Please tell me why it is.

I wrote like this ans = [[0,0],[0,0]] ans[0][0] += 1 I supposed it's change to [[1,0],[0,0]], because ans[0][0] is 0. However it was change to [[1,0],[1,0]]. I'd like you to tell me what the correct way to write it is.

S0ma
  • 11
  • 3
  • 6
    You didn't write `ams = [[0, 0], [0, 0]]`. If you would, this wouldn't have happened. You probably wrote something that you think is equivalent (e.g. `[[0, 0]] * 2`) but it is not, because it does not copy the inner list, only reference to it. – Chayim Friedman Jul 26 '23 at 08:42
  • 2
    please add minimum reproducible code https://stackoverflow.com/help/minimal-reproducible-example. Your issue is not reproducible, you probably write different code ``` >>> ans = [[0,0],[0,0]] >>> ans [[0, 0], [0, 0]] >>> ans[0][0] += 1 >>> ans [[1, 0], [0, 0]] ``` – marcadian Jul 26 '23 at 08:43
  • I wrote like this 'ans = [[0]*(6//3)]*(6//3)' and ' ans[1//3][1//3] +=1', and it's changed to '[[1, 0], [1, 0]]' – S0ma Jul 26 '23 at 08:46
  • may you miss something typo – Dejene T. Jul 26 '23 at 08:46
  • 1
    *what the correct way to write it is.* This is the correct way to write it, since this code doesn't reproduce the issue you are describing. – Guy Jul 26 '23 at 08:47
  • @Habor so as @Chayim said, you didn't write `ans = [[0,0],[0,0]]` you wrote `ans = [[0]*(6//3)]*(6//3)` instead. You might want to edit your question and put the code you actually have – Sembei Norimaki Jul 26 '23 at 09:22

1 Answers1

0

I wrote like this 'ans = [[0](6//3)](6//3)' and ' ans[1//3][1//3] +=1', and it's changed to '[[1, 0], [1, 0]]' –

That is not equals to ans = [[0,0],[0,0]]. Both ans[0] and ans[1] are pointing to the same list. I believe it's because you do [[0, 0]] * 2, it points to the same list reference, you can confirm if 2 objects pointing to same place with

>>> id(ans[0])
4336826632
>>> id(ans[1])
4336826632

Here's a simplified version of your issue:

>>> a = [0]
>>> b = a   # both b and a are referring to the same place in memory
>>> b[0] += 1  # doing this is same as referencing using a, i.e a[0] += 1
>>> a
[1]
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
marcadian
  • 2,608
  • 13
  • 20