+ 2

Python - what is the difference between those statements?

What's the difference between A=B and A = B[:]?

2nd Sep 2019, 1:41 PM
Gabriel Wiedemann
Gabriel Wiedemann - avatar
9 odpowiedzi
+ 3
When you make a copy of a list: A = B.copy() It makes sure that A and B are not the same. It does not make sure, that their items are copied too. Thus A[1] and B[1] are still the same, even though A and B are not the same. It can be quite complicated, but I think there is a solution in module "copy".
2nd Sep 2019, 2:18 PM
Seb TheS
Seb TheS - avatar
+ 7
Let's assume B is an ordered iterable. This: A = B will give A the original B. changes on A will also change B and changes on B will also change A. This: A = B[:] will give A only a copy of B. changes on A will not change B and changes on B will not change A. BUT changes on A's items can change B's items and changes on B's items can change A's items. This: from copy import deepcopy A = deepcopy(B) will also give A a copy of B, but it will also make copies of all the mutable items in the list. changes on A will not change B and changes on B will not change A. AND changes on A's items will not change B's items and changes on B's items will not change A's items.
2nd Sep 2019, 1:47 PM
Seb TheS
Seb TheS - avatar
2nd Sep 2019, 2:25 PM
Seb TheS
Seb TheS - avatar
+ 2
I get it now, b= a[:] is the same as b= copy(a). And if I don't want to keep references to list inside lists, then I use a=deepcopy (b).
2nd Sep 2019, 2:54 PM
Gabriel Wiedemann
Gabriel Wiedemann - avatar
+ 2
Gabriel Yes, b = a[:] and b = a.copy() don't have much difference, except for which datatypes they can be used, but I would recommend a.copy() because it's more readable. Here are some speed comparisons for different methods with same result: https://code.sololearn.com/cvlGwbcjQXOO/?ref=app
2nd Sep 2019, 9:10 PM
Seb TheS
Seb TheS - avatar
+ 1
Solution: from copy import deepcopy a = [5, [6, 7]] b = deepcopy(a)
2nd Sep 2019, 2:23 PM
Seb TheS
Seb TheS - avatar
0
Ok, but I still have a question about it, something is still not clear. Here is a complete code that shows where I don't get it... https://code.sololearn.com/cP3lHeM48mR2/?ref=app
2nd Sep 2019, 2:09 PM
Gabriel Wiedemann
Gabriel Wiedemann - avatar
0
Yeah, I saw that as a[1] is a list, a[1] IS the same as b[1], so if a change a[1], it also changes b[1]. But if I change other indexes of a that are a list themselves, the changes does not apply to b. I Just don't know exactly why that works that way, this could cause some trouble if this is not clear for me...I'm gonna check the module "copy", I hope the detail I am searching for is there, thanks for the help.
2nd Sep 2019, 2:30 PM
Gabriel Wiedemann
Gabriel Wiedemann - avatar
0
Sorry, you posted more stuff before I give you a feed back, I will check that out
2nd Sep 2019, 2:32 PM
Gabriel Wiedemann
Gabriel Wiedemann - avatar