python 2d list initialization error by using arr = [0 * size] * size

Viewed 20

I was trying to initialize a 2D list in python by arr = [0 * size] * size. When I assigned value 1 to the position arr[0][0], arr[1][1],arr[2][2]....., somehow all the positions were assigned to 1. I am confused which part I did wrong. Thank you

n = 3
dp = [[0] * n] * n
print (dp)
for i in range(n):
    dp[i][i] = 1
print(dp)

#result from pycharm
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]
1 Answers

The wrong part is the initialization of the 2D array. Use dp = [ [0] * n for _ in range(n) ] instead.

Your code does not work because the last * does a shallow copy. It copies the address of the object (list), so all n lists are in fact the same one.

Related