1

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]]
Zeren Li
  • 11
  • 2
  • 2
    Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – OrenIshShalom May 26 '22 at 06:30

1 Answers1

0

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.

Albert Rial
  • 106
  • 7