0

I'm trying to understand (on the level of principle) the difference between assignment between (say) integers variables and list variables.

Integer case:

a=6
b=a
print(b) #prints 6
a=7
print(b) #prints 6

That makes sense to me with this logic: in the original b=a, b was given the same value as a (6), not identified with a. So if I change the value of a, the value of b does not change: b is not the same thing as a.

List case:

L=[1,2]
M = L 
print(M)
L.append(6)
print(M)

This can make sense with this logic: in M=L I'm forcing M to literally be the same object as L is, I'm identifying it with L. So if L changes, so does M.

What doesn't make sense (to me) is why I need different logic in different cases. (Probably this has to do with integers being "immutable" and lists "mutable" but I don't see how that bears on this.) Can someone point me to a explanation? What is the principle behind the difference in behaviors? (I'm not looking so much for how the technical difference in implementation of integers and lists leads to the difference, but for the reason things were designed this way. What's the logic?)

asked May 14, 2017 at 16:26
0

3 Answers 3

4

Every name is a variable holding a reference to some object.

What happens in the first case is that

a = 6
b = a # (a and b point to the same object)

But here, you are changing what a points to:

a = 7

Compare this to the second/list situation, where you actually call the method on the first object. You didn't update the reference as you did in the case with the integers.

L = [1,2]
M = L # here you introduce a new name, referencing the same object as L.
L.append(6) # update that same object.
print(M) # you print that same object
answered May 14, 2017 at 16:33
2

You don't have different logic in different cases here. Lists and integers work in exactly the same way as far as assignment is concerned. If, in your second snippet, to assigned a different list to L in the penultimate line, the two variables would be unrelated.

But lists have an additional capability, which integers and strings don't have, which is that you can modify them. That's all you're​ seeing here.

answered May 14, 2017 at 16:35
0

Well M = L gets what L currently is and after it prints M you then append 6 to L but this will only effect L because M had only received what L previously was, but if you did M = L again after the append it would print the updated version of the list. Basically if you get a xvariable set to a yvariable and then that yvariable updates the xvariable will not update because you will have to update the xvariable again but this is usually this happens by it self if a loop is being used

answered May 14, 2017 at 16:32

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.