+ 6
Python output
Expected output : [[8],[9]] My output : [[8,9],[8,9]] ans=[[]]*2 ans[0].append(8) ans[1].append(9) print(ans) Why is the output wrong? What should be done to get the expected output.
9 Answers
+ 5
This is because when you do the "*2", what you're duplicating is in fact the reference to the list, because lists are mutable types. Therefore, any change to one is a change to another.
+ 3
Jay Matthews can you explain it more precisely. Why isn't my approach correct.
+ 3
ans=[[],[]]
ans[0].append(8)
ans[1].append(9)
print(ans)
+ 2
I'm not good at Python, but I found that ans[0] and ans[1] refer to the same object. It might be the reason of the output. I don't know why though.
https://code.sololearn.com/cnk27rmgF36s/?ref=app
+ 2
this is working
A=[]
B=[]
C=[]
A.append(8)
B.append(9)
C.append(A)
C.append(B)
Print(C)
+ 1
I have written a mini tutorial about that sort of problems.
After reading it, you should understand what's going wrong here.
https://code.sololearn.com/c89ejW97QsTN/?ref=app
+ 1
to fix this, you can do:
a1=[]
ans=[a1[:], a1[:]]
ans[0]. append(8)
ans[1]. append(9)
print(ans)#[[8], [9]]
+ 1
ans =[ [[]],[[]] ]
ans[0].append(8) is applied to both tables so you have: ans = [ [8,[]],[8,[]] ]
at the next step you replace the scond element of each table (which are tables) by 9
so you get [[8,9],[8,9]]
0
ans [[]] * 2 is basically the same as:
a1 = []
ans = [a1, a1]
To fix this, you can do:
a1 = []
ans = [a1[:], a1[:]]
ans[0].append(8)
ans[1].append(9)
print(ans) #[[8],[9]]