matrix = [[0]*1005]*1005
and
matrix = [[0 for _ in range(1005)] for _ in range(1005)]
I found if i using the former to initial array, and run matrix[1][1] = 1 it will set the second column in every row to 1. And the second performed as i wished. I can’t figure out why?
[[0] * 1005] * 1005will create an array of 1005 references to an array with 1005 zeroes. They’re all the same reference, and so changing one will change all the others. You can shorten your working code to this, though:This is pretty much the only warning anybody ever gives you about the list multiplication syntax, actually 🙂