+ 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)
4 Antworten
+ 4
you can solve the problem by adding an
import copy
and replacing
j=r
with
j=copy.copy(r)
(btw 100th post)
+ 3
The problem is that j is always referring to the same list, so it always adds the 3 to the same list
+ 3
instead of using the copy module, you could also do
j=r[:]