Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does the logic behind this piece of code work?

I have typed out the following code.

la = [1,[2,[3,[4]]]]

lb = [la[1], la[1][1]]

print(la)

lb[0][1]=9

print(la)

I was expecting la to remain as in the original first line, but it changed as shown below.

[1, [2, [3, [4]]]]

[1, [2, 9]]

Does this have to do with shallow and deep copy? I can’t seem to wrap my head around what’s going on. Apologies for the formatting, I’m trying to fix it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

So the answer gives you the solution to how to properly copy data in your case, but it does not explains what happens. I commented your script to get an insight into what you are doing:

A comment on notation:

ptr(X) means a reference to somewhere in memory which I call X.
X is a un-named address, if you will.

Don’t look to much into the words "pointer" and "reference" as I have only used them to explain a concept, not as strict keywords like one might think if coming from C++ or similar.

la = [1,[2,[3,[4]]]]

# la = [ 1 , ptr(X) ]
# X  = [ 2 , ptr(Y) ]
# Y  = [ 3 , ptr(Z) ]
# Z  =  [ 4 ]
print(la)


lb = [la[1], la[1][1]]

# lb = [ ptr(X) , ptr(Y)  ]

lb[0][1]=9

# lb[0]    is  ptr(X)
# lb[0][1] is  X[1] is ptr(Y)
# lb[0][1] = 9 --> X = [2,9]

# now if we look at how la is defined
# la = [ 1 , ptr(X) ]
# X  = [ 2 , ptr(Y) ]

# meaning that now X is [2,9] and ptr(X) points to [2,9], 
# so la is

# la = [ 1 , ptr(X) ]
# X  = [ 2 , 9 ]

# so if we print la we get
# [1,[2,9]]

# et voila
print(la)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading