+ 3

Why b also change?Please explain me!

a = [[1,2],[3,4]] b = a.copy() a[0].reverse() print(a) print(b) Output>>[[2,1], [3,4]] >>[[2,1], [3,4]]

20th Apr 2020, 9:12 AM
Moe Kyaw Oo
Moe Kyaw Oo - avatar
10 Respostas
+ 8
Because you have made a shallow copy instead of a deep copy. You made a new outer list, but it contains references to the same inner lists. More details: https://code.sololearn.com/c89ejW97QsTN/?ref=app
20th Apr 2020, 9:14 AM
HonFu
HonFu - avatar
+ 5
If you want to make a deep copy of that list a, one quick way to do it is: b = [l[:] for l in a]
20th Apr 2020, 11:38 AM
HonFu
HonFu - avatar
+ 1
HonFu Thank you very much
20th Apr 2020, 11:43 AM
Moe Kyaw Oo
Moe Kyaw Oo - avatar
+ 1
These things are confusing in the beginning, but I am sure you'll understand it much better after studying my tutorial up there. This is a topic that will come up again and again, so the effort will definitely not be wasted. :)
20th Apr 2020, 11:56 AM
HonFu
HonFu - avatar
0
I am reading your explanations now.But I am wondering What am I supposed to do now?
20th Apr 2020, 9:43 AM
Moe Kyaw Oo
Moe Kyaw Oo - avatar
0
What do you mean? Supposed to do with what? What do you *want* to do?
20th Apr 2020, 9:57 AM
HonFu
HonFu - avatar
0
If I change a[0] , I want b[0] remains unchanged.
20th Apr 2020, 10:26 AM
Moe Kyaw Oo
Moe Kyaw Oo - avatar
0
HonFu Sorry my English is not very good. When I replace third line with a[0] = a[0][::-1] , b remains unchanged. What is the difference? a = [[1,2],[3,4]] b = a.copy() a[0] = a[0][::-1] print(a) print(b) Output>>[[2,1], [3,4]] >>[[1,2], [3,4]]
20th Apr 2020, 11:38 AM
Moe Kyaw Oo
Moe Kyaw Oo - avatar
0
Because it is list. Direct equal do not create copy. Make slicing of list. In this case new copied list created
21st Apr 2020, 8:03 PM
george
george - avatar