Home > database >  for loop update list in python is not working
for loop update list in python is not working

Time:02-26

a=[[1]]

current=a[-1]
a.pop(-1)
edge=[2,3,4,5,6,7,8,9,10]
for j in range(len(edge)-1,-1,-1):
   current.append(edge[j])
   print(current)
   a.append(current)
   current.pop(-1)   

above code gives me a=[[1],[1],...,[1]], but I thought that s=[[1,10],[1,9],...,[1,2]]..I thought that python read the code from the beginning so those code is correct..could you tell me how to get a=[[1,10],[1,9],...,[1,2]]? thanks in advance! (I added print(current)<<this line to check whether it is appended correctly and it is actually adjusted correctly and gave me [1,10] but when a.append(current) it is added as [1].)

CodePudding user response:

Just change a.append(current) to a.append(current.copy()), when you add current to a the reference of object is added and when you pop the last item of current also the item in a is changed. The another way is: Solution 1:

   a.append(current.copy())
   current.pop(-1)

Way 2:

   a.append(current)
   current = [1]

Result of print(a):

[[1, 10], [1, 9], [1, 8], [1, 7], [1, 6], [1, 5], [1, 4], [1, 3], [1, 2]]
  • Related