I come across the following python puzzle:
x=4*[[]] # x is now [[],[],[],[]]
for i in range(len(x)): x[i]+=[i];
print x;
# this returns [[0,1,2,3],[0,1,2,3],[0,1,2,3],[0,1,2,3]]
now if I do instead:
x=[[],[],[],[]];
for i in range(len(x)): x[i]+=[i];
print x;
# this returns [[0],[1],[2],[3]]
The question is, why?
I also find that if the code is changed to
x[i] = x[i] + [i]
then we have in both cases
[[0],[1],[2],[3]]
Does someone know why python behaves in this way?
Edit: the first half of my question is answered in the duplicate reference, and the second half is explained by @joriki below.