Reputation: 99
I cannot understand why the piece of code described below does what it does
import numpy as np
N = 2
A=[];
B=[];
for i in range(N):
B.append(i)
A.append(B)
The first time the for loop runs (for i =0), A = [[0]]. The second time the loop runs (for i =1), B = [0,1] and so I expect A = [[0],[0,1]], since we are appending B to A. However, when I print A, I get A = [[0,1],[0,1]]. Why do I not get the form I expect?
Upvotes: 0
Views: 46
Reputation: 2426
A
and B
here are pointing to objects in memory. So, if the object itself is modified in memory, all variables pointing to that object will show the updated value.
Now let's look at the code:
B.append(i)
-> list B
is appended with value of i.
A.append(B)
-> list A
is appended with reference of B. But the object itself referenced by B
is getting modified in each iteration, and hence the most updated value of B
is shown as each element of A
at each level of iteration. If you run the loop for more iterations and print A
, you'll notice this behavior clearly.
One way of overcoming this issue is appending A
with a copy of B
.
N = 4
A=[]
B=[]
for i in range(N):
B.append(i)
A.append(B.copy())
print(A)
# Output:
# [[0]]
# [[0], [0, 1]]
# [[0], [0, 1], [0, 1, 2]]
# [[0], [0, 1], [0, 1, 2], [0, 1, 2, 3]]
Upvotes: 3