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 ???
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.