How to modify value in Python 2D list

Method one(Be careful !!!)

In this method, each row references to the same column. This means, even if we update only one element of the array, it will update same column in our array.

mylist = [[0] * 4 ] * 3
mylist[1][1] = 9
print(mylist)

Output:

[[0, 9, 0, 0], [0, 9, 0, 0], [0, 9, 0, 0]]   

Method two - Using List Comprehension

Here we use list comprehension by applying loop for a list inside a list and hence creating a 2-D list.

mylist = [[0] * 4 for _ in range(3)]
mylist[1][1] = 9
print(mylist)

Output:

[[0, 0, 0, 0], [0, 9, 0, 0], [0, 0, 0, 0]]

Reference