0
x = [1,3,6,[18]]
y = list(x)
x[3][0] = 15
x[1] = 12
print(y)

The output is [1,3,6,[15]], why are not all the changes reflected on y.

noobie
  • 41
  • 1
  • 4
  • 3
    By doing `list(x)` you are making a *copy* of the list. Try just doing `y=x`. – gen_Eric Dec 20 '21 at 18:15
  • 1
    I assume you are asking why your changes in x did not change the value of y. You set y to the value of x and that is it. Nothing you do to x will affect y unless you set y to the pointer of x. I would explain your problem more clearly in the future – Daniel me Dec 20 '21 at 18:16
  • 1
    You created a shallow copy of x and stored it in y. – luk2302 Dec 20 '21 at 18:16
  • 1
    https://stackoverflow.com/q/70410679/17635987 – kirjosieppo Dec 20 '21 at 18:19
  • even if y is a copy, x[3][0] gets reflected on y but not x[1], that is actually my question. – noobie Dec 20 '21 at 18:21
  • Because you created a *shallow* copy, not a deep one. – luk2302 Dec 20 '21 at 18:25
  • 2
    Does this answer your question? [Why does list() function is not letting me change the list](https://stackoverflow.com/questions/70410679/why-does-list-function-is-not-letting-me-change-the-list) – luk2302 Dec 20 '21 at 18:25

1 Answers1

0

y = list(x) creates a (new) list from the iterable elements in x - even if x is already a list. This is different from y = x where y now just references the same list object as x.

This also explains why the last element is changed in your example. The last element in the x-list is actually a reference to another list. When this reference is copied as part of the y = list(x) operation it behaves like the y = x case, so now you have two references to this one list, one in x[3] and the other one in y[3].

So when you access this list reference through x[3] and change the content, y[3] will show the changed content.

To make the difference clear, replace x[3][0] = 15 with x[3] = [15]. Now you have changed the list reference in x[3] to a reference to a new list while y[3] still references the original sublist and is thus independent now.

You may want to read the relevant documentation

TToni
  • 9,145
  • 1
  • 28
  • 42