I have initialized a 2D list with 2 different approaches here.
But when I assigned some values, both are not outputting the same result.
I see the result in lines 5
and 10
have different values.
At line 5
all 2D list values got changed to 1
.
Why it is happening so?
1 lst = [[0]*3]*4
2 print(lst)
3 lst[1][0], lst[1][1], lst[1][2] = 1, 1, 1
4 print(lst)
5 # [[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]
6 lst = [[0,0,0] for _ in range(4)]
7 print(lst)
8 lst[1][0], lst[1][1], lst[1][2] = 1, 1, 1
9 print(lst)
10 # [[0, 0, 0], [1, 1, 1], [0, 0, 0], [0, 0, 0]]