I just wanted to know how do we get the following output. The given below is a Python code:
x=[1,3,6,[18]]
y=list(x)
x[3][0]=15
x[1]=12
print(y)
Output is:
[1,3,6,[15]]
Why x[1]=12
didn't make any changes in the list y? But why x[3][0]=15
changed the element in list y? Can you give a detailed and simple explanation to this? Why???
CodePudding user response:
Imagine each element is a variable:
x = [a,b,c,d] # 1,3,6,[18]
you copy that as y
so you have
y = [a,b,c,d] # 1,3,6,[18]
when you do x[3][0] = 15
you are changing the first element of d
. notice that d
is still the variable d
, you changed its content but it's still the same d
in both lists.
Now you change the second element of x
x = [a,e,c,d] # 1,12,6,[15]
but y
is still
y = [a,b,c,d] # 1,3,6,[15]
EDIT: adding a non-code example to make it maybe more clear
let's say x
is a list with:
- a paper that says
1
- a paper that says
3
- a paper that says
look at that notebook over there, whatever's in there is my value
when you copy x
as y
, you have:
- a paper that says
1
(a copy) - a paper that says
3
(a copy) - a paper that says
look at that notebook over there, whatever's in there is my value
(this is a copy, but both reference the same notebook)
when you do x[2][0] = 1
you walk to where the notebook is and change the content, both x
and y
still tell you to go to that same notebook to know what's in there, you didn't change the 3rd paper, you followed its instruction and changed the content of the notebook
when you do x[1] = 6
, you are changing the second element of x
with a new paper that says 6
, but you didn't change the one in y
because it's a different paper (a copy of the original)