How does the logic behind this piece of code work?

Question:

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.

Asked By: moonmoon

||

Answers:

You should use copy() in your case:

lb = [la[1].copy(), la[1][1].copy()]

Assignment statements in Python do not copy objects, they create bindings between a target and an object.

See doc.

Answered By: Aymen

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)
Answered By: Fra93
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.