python - Create new list in for loop -
this question has answer here:
i'm trying create new list changing other in loop, using append method. have trouble it.
my simple code:
l1=[] l2=[0,0] in range(4): l2[0]+=1 l1.append(l2) print l2 print l1
return:
[1, 0] [2, 0] [3, 0] [4, 0] [[4, 0], [4, 0], [4, 0], [4, 0]]
but expected list l1 this: [[1,0], [2,0], [3,0], [4,0]] made mistake?
you appending reference list. , since, @ end of loop, value of l2
[4,0]
, each list inside l1
[4,0]
you can append copy of list of list()
built-in method or, using slicing notation shown below
l1=[] l2=[0,0] in range(4): l2[0]+=1 l1.append(list(l2)) # or l1.append(l2[:]) print l2 print l1
if not able understand idea, can use viz mode of codeskulptor , run code line line, understand properly.
Comments
Post a Comment