+ 1

Point out my mistake in code:

Q=[] r=[1, 2] i=0 while i<3: j=r j.insert(i, 3) Q.append(j) i=i+1 print(Q) My desire output is : >> [[3,1,2],[1,3,2],[1,2,3]] >> Which can be obtained by: Q=[] i=0 while i<3: j=[1, 2] j.insert(i, 3) Q.append(j) i=i+1 print(Q)

7th Jul 2017, 4:20 PM
Pratik Jadhav
Pratik Jadhav - avatar
4 ответов
+ 4
you can solve the problem by adding an import copy and replacing j=r with j=copy.copy(r) (btw 100th post)
8th Jul 2017, 8:41 AM
Supersebi3
Supersebi3 - avatar
+ 3
The problem is that j is always referring to the same list, so it always adds the 3 to the same list
8th Jul 2017, 8:40 AM
Supersebi3
Supersebi3 - avatar
+ 3
instead of using the copy module, you could also do j=r[:]
10th Jul 2017, 5:43 PM
Supersebi3
Supersebi3 - avatar
7th Jul 2017, 4:33 PM
Michael55555
Michael55555 - avatar