To manually initially an N x N
list of 0
values, you can do the following
mylist = [[0 for x in range(n)] for y in range(n)]
Printing a 3x3 version you'd see:
>>> mylist = [[0 for x in range(3)] for y in range(3)]
>>> print(mylist)
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Change any value, all good:
>>> mylist[0][1] = 1
>>> print(mylist)
[[0, 1, 0], [0, 0, 0], [0, 0, 0]]
Now, I know you can initialize a size N list with:
mylist = [0] * n
And to create an NxN the following appears to work (same 3x3 example)
>>> mylist = [[0] * 3] * 3
>>> print(mylist)
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
However, modifying this list produces unexpected results
>>> mylist[0][1] = 1
>>> print(mylist)
[[0, 1, 0], [0, 1, 0], [0, 1, 0]]
Can someone explain why the second way of initializing the NxN list acts in this manner?