Chanaging member of list impacting copy partially | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Chanaging member of list impacting copy partially

Running below code    x = [1, [2,3, [4,5,6]]]    y = x[:]    x[0] = 55   # impacted only x    x[1][0] = 66   # impacted x & y    x[1][2][1] = 79   # impacted x & y    print(x,y) This code gives the result as below    [55, [66, 3, [4, 79, 6]]], [1, [66, 3, [4, 79, 6]]] x[0] = 55 not impacted y. But x[1][0] = 66 & x[1][2][1] = 79 impacted both x & y. Can anyone help with correct reason?

18th Apr 2020, 4:13 AM
Sreeraj V A
Sreeraj V A - avatar
1 Answer
+ 1
Line 4 and 5 affect both x and y because they refer to the same lists in lists. When copied y = x[:], the 2 lists inside of x are not created as new lists but only the reference to them is passed to y. a = [4, 5, 6] b = [2, 3, a] x = [1, b] y = x[:] # x and y refer to a and b # altering a and b impacts x and y
19th Apr 2020, 8:43 PM
Lisa
Lisa - avatar