I need to initialize 2d array with list.
For example 2X3 array: [[0,0,0], [0,0,0]]
First attempt:
In: a1 = [[0]*3]*2
In: a1[0][0] = 100
In: a1
Out: [[100,0,0], [100,0,0]]
This is strange. So I checked:
In: a1 = [[0]*3]*2
In: id(a1[0][0])
Out: 4518461984
In: id(a1[1][0])
Out: 4518461984
Same address.
Second attempt:
In: a2 =[[0]*3 for i in range(2)]
In: a2[0][0] = 100
In: a2
Out: [[100, 0, 0], [0, 0, 0]]
Right.
Let me check memory address again:
In: a2 =[[0]*3 for i in range(2)]
In: id(a2[0][0])
Out: 4518461984
In: id(a2[1][0])
Out: 4518461984
Well, strange. Same address again. I expected different addresses. My initial guess is that the address returned is the address of pointer to value. Then how can I retrieve the address of the slot?
Is there anyone who can explain the workings of Python that caused this behavior? In Python, I think it's very hard to know which is pointer and which is value.