+ 1

why the answer is wrong?!

In the below code, I'll expect the answer is [[0, 1, 0, 0, 0], [1,0, 2, 0, 0], [0, 2, 0, 3, 4], [0, 0, 3, 0, 0], [0,0, 4, 0, 0]] , but the answer will be different. def filler(mat,zar,n): new=[[0]*n]*n for k in mat: for i in range(n): for j in range(n): if k[0]-1 == i and k[1]-1 == j: new[i][j] = zar[mat.index(k)] new[j][i] = zar[mat.index(k)] return new #------------------------------------------------------- a = [[1, 2, 1, 2], [2, 3, 1, 2], [3, 4, 1, 2], [3, 5, 1, 2]] b = [1,2,3,4] c = 5 f = filler(a,b,c) print(f) #------------------------- please help me.

16th Apr 2019, 11:32 AM
رضا شفقی
رضا شفقی - avatar
2 ответов
+ 2
new=[[0 for i in range(n)] for j in range(n)] Your code fills "new" with five references to the same list. If you change one of them, you change all of them.
16th Apr 2019, 11:48 AM
Anna
Anna - avatar
+ 2
thanks Anna
16th Apr 2019, 12:03 PM
رضا شفقی
رضا شفقی - avatar