+ 1

Question about lists

I thought the output would be [3,4,3,1,2], but instead it is [3,4,3,3,4]. When changing x, why would y also change? Also, how can I make a copy of a list that will not change when the original list changes? x=[1,2,3,4,5] y = x x[0:2]=y[2:4] x[3:5]=y[0:2] print(x) https://code.sololearn.com/cwZKbQMh872P/?ref=app

29th Sep 2018, 6:04 AM
chunngai chan
chunngai chan - avatar
4 ответов
+ 2
chunngai chan y=x create only shallow copy of the variable you need deep copy of the object and remember y=x[:] KrOW is coded is also shallow copy not a deep copy if your list is nested it will also change.e.g x=[[1,2],[3,4]] y=x or y=x[:] x[1][1]='m' now when you print y it will also change so try copy module to create deep copy of the variable or object. import copy y=copy.deepcopy(x) now y is independent from x even x in nested.
29th Sep 2018, 4:35 PM
Maninder $ingh
Maninder $ingh - avatar
+ 2
with y = x you assign SAME object (x) to y then any edit on one will reflect on other (i repeat they are SAME). For get what you want, you have to copy and you can do this so y = x[:] Now though x and y will have same items, they are DIFFERENT list objects
29th Sep 2018, 6:16 AM
KrOW
KrOW - avatar
+ 1
thx!
29th Sep 2018, 6:22 AM
chunngai chan
chunngai chan - avatar
0
👍👍👍
29th Sep 2018, 6:22 AM
KrOW
KrOW - avatar