1
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].)

1
  • You keep spending the same list to a Commented Feb 26, 2022 at 4:19

1 Answer 1

1

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]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.