+ 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.

22nd Mar 2020, 5:55 AM
Manoj
Manoj - avatar
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.
22nd Mar 2020, 11:37 PM
šŸ‘‘ Prometheus šŸ‡øšŸ‡¬
šŸ‘‘ Prometheus šŸ‡øšŸ‡¬ - avatar
+ 3
Jay Matthews can you explain it more precisely. Why isn't my approach correct.
22nd Mar 2020, 6:34 AM
Manoj
Manoj - avatar
+ 3
ans=[[],[]] ans[0].append(8) ans[1].append(9) print(ans)
23rd Mar 2020, 3:03 AM
Ragul.M
Ragul.M - avatar
+ 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
22nd Mar 2020, 7:12 AM
ä½ ēŸ„é“č¦å‰‡ļ¼Œęˆ‘也ę˜Æ
ä½ ēŸ„é“č¦å‰‡ļ¼Œęˆ‘也ę˜Æ - avatar
+ 2
this is working A=[] B=[] C=[] A.append(8) B.append(9) C.append(A) C.append(B) Print(C)
23rd Mar 2020, 1:51 AM
Bala Chinna
Bala Chinna - avatar
+ 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
22nd Mar 2020, 10:14 AM
HonFu
HonFu - avatar
+ 1
to fix this, you can do: a1=[] ans=[a1[:], a1[:]] ans[0]. append(8) ans[1]. append(9) print(ans)#[[8], [9]]
23rd Mar 2020, 10:42 AM
Golden Sharma
Golden Sharma - avatar
+ 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]]
23rd Mar 2020, 11:31 AM
10ce097
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]]
22nd Mar 2020, 9:25 PM
CeePlusPlus
CeePlusPlus - avatar