+ 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]]
9 Answers
+ 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
+ 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]
+ 1
HonFu Thank you very much
+ 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. :)
0
I am reading your explanations now.But I am wondering What am I supposed to do now?
0
What do you mean? Supposed to do with what? What do you *want* to do?
0
If I change a[0] ,
I want b[0] remains unchanged.
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]]
0
Because it is list. Direct equal do not create copy. Make slicing of list. In this case new copied list created