1

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. What is the correct reason?

halfer
  • 19,824
  • 17
  • 99
  • 186
sre
  • 249
  • 1
  • 12
  • 6
    Because [:] copy the list x, but the inner list still point to the same list. – Frank Apr 18 '20 at 04:13
  • 2
    Because `y = x[:]` makes a ***shallow copy***. So you get ***list aliasing*** when you assign to its elements that are sublists. – smci Apr 18 '20 at 04:16

1 Answers1

2

When you copy x into y, the inner list is not copied. In other words, x[1] and y[1] are pointing to the same object.

visualizing your code at http://www.pythontutor.com/ should help to understand

zetamoon
  • 66
  • 5