0

Below two snippets create list of list of dimension(5x5) but they producing different result

  • a = [[0]*5]*5
  • b = [[0 for x in range(5)] for y in range(5)]

Both will given me same list:

>>>a
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>>b
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

But when I do following both give different result:

a[0][0] = 1
[[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]]
b[0][0] = 1
[[1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

Why so ?

Sid
  • 589
  • 6
  • 20
  • 1
    Be sure to read the duplicate question and its answers. The short answer to your question is that the two lists you created are not the same, even though when printed they look the same. – Rory Daulton Sep 17 '17 at 18:58
  • Yes, I understood the concept. Thanks a lot! – Sid Sep 18 '17 at 12:37

0 Answers0