This is my code:
n = 5
r = 6
C1 = [[0 for x in range(r+1)] for x in range(n+1)]
print(C1)
print()
C1[4][3] = 4
print(C1)
print()
print()
C2 = [[0] * (r+1)] * (n+1)
print(C2)
print()
C2[4][3] = 4
print(C2)
This is the output:
[[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, 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, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 4, 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, 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, 0, 0]]
[[0, 0, 0, 4, 0, 0, 0], [0, 0, 0, 4, 0, 0, 0], [0, 0, 0, 4, 0, 0, 0], [0, 0, 0, 4, 0, 0, 0], [0, 0, 0, 4, 0, 0, 0], [0, 0, 0, 4, 0, 0, 0]]
Why is it that when I use the 'for-range' way, I'm getting the right answer, but the []*n method is giving me the wrong answer? Both produce the same 2D array but when I try to modify it, I'm getting 2 different results!