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.
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.
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