0
x=[1,[2]]
y=list(x)
x[0]=-1
x[1][0] = -1
print(y)

I thought the answer would be [1,[2]] as the changes were made after declaring variable y but the output i get is [1,[-1]]. Please explain the reason.

Cardstdani
  • 4,999
  • 3
  • 12
  • 31
sachin
  • 17
  • 2

1 Answers1

3

When you assing y you are not making a new list, you are pointing to the same object as x. So when you update x, y is now pointing to the "new" version of x

edit-- @S3DEV pointed out that this answer is is not that precise, list(x) has made a copy (new object) of x; albeit, a shallow copy. So it has made a copy of x, but not the second element of the list witch is an other list. y[1] is pointing to the same object that x[1] is pointing to.

Bendik Knapstad
  • 1,409
  • 1
  • 9
  • 18
  • 3
    In this case, no; this is incorrect. `list(x)` has made a copy (new object) of `x`; albeit, a *shallow copy*. – S3DEV Jun 27 '22 at 07:59
  • 2
    To follow on from @S3DEV comment, `y[1]` is pointing to the same list as `x[1]` – Nick Jun 27 '22 at 08:01
  • 1
    … and `y[0]` is a new object. So it’s really a mishmash of new objects (`y[0]`) and references (`y[1]`) – S3DEV Jun 27 '22 at 08:02