0

I am a fresher using Python3.

I don't quite understand this:

a = [[0]*4]*1
b = [[1,2],[3,4]]

if I do:

a[0][0] = b[0][0]

Instead of only updating a[0][0] with 1: a=[[1],[0],[0],[0]]

the whole list became:

a=[[1],[1],[1],[1]]

Can anyone advise how I can initiate a proper MxN matrix without getting this error?

Thanks a lot!

  • 4
    I can't reproduce your code, you must've done `a = [[0]] * 4`. – U13-Forward Oct 05 '21 at 03:24
  • Thank you very much for your prompt answer. I was using a = [[0] * 4] * 1 to initiate a 4x1 list. Can you please advise how I can initiate an MxN list without getting this strange behaviour? – user17076059 Oct 05 '21 at 03:40
  • [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/q/240178) – U13-Forward Oct 05 '21 at 03:42

1 Answers1

1

Upon reconstruction, with the code:

a = [[0],[0],[0],[0]]
b = [[1,2],[3,4]]

a[0][0] = b[0][0]

print(a)

The output was the expected: [[1], [0], [0], [0]]

Try copying/pasting this code into your IDE and seeing the output, if you still get the a=[[1],[1],[1],[1]], then it could be a problem with your python environment or something different entirely. Unless I've missed something.

PotSkill
  • 221
  • 3
  • 11
  • Thank you for your prompt reply! I initiated `a` with [0]*4 so that I got the error. sorry for not making it clear in the question. Thanks for your time :) – user17076059 Oct 05 '21 at 03:47
  • Do you still get an error? Because otherwise just initiate ```a``` with my code above. – PotSkill Oct 05 '21 at 23:06