3
votes

Is there a reason that assigning a list to another list and changing an item in one reflects the change in both, but changing the entire list of one does not reflect the change in both?

a=5
b=a
a=3
print b #this prints 5

spy = [0,0,7]
agent = spy
spy[2]=8
print agent #this prints [0,0,8]

spy = [0,0,7]
agent = spy
spy = "hello"
print agent #this prints [0,0,7]
3

3 Answers

7
votes

Your first mutates the object, your second rebinds the name.

(list that spy contains)[2]=8

(name called "spy")= "hello"

2
votes

References in Python are much easier to understand if you forget everything you know about pointers, addresses, passing by value and passing by reference, and think of it just as labels and objects, or names and objects.

Follow this:

a=5
b=a
a=3
print b #this prints 5

You have label 'a' put on 5, then 'b' put on the same object 'a' is, therefore 5. Then 'a' is removed and put on 3. 'b' still is on 5 and moving 'a' to something else doesn't affect it.

spy = [0,0,7]

You have name 'spy' put on a list [0, 0, 7]

agent = spy

You have name 'agent' put on the same list [0, 0, 7]

spy[2]=8
print agent #this prints [0,0,8]

You put the index 2 label from the list on 8. Since agent and spy are both names for the same list, you'll see the change in both when you print it.

spy = [0,0,7]

You have name 'spy' on a list [0, 0, 7]

agent = spy

You have name 'agent' on the same list [0, 0, 7]

spy = "hello"

Now you have name 'spy' removed from the list and put on a string "hello". The list still has the label 'agent' assigned to it.

print agent #this prints [0,0,7]

Got it?

1
votes

When you assign a list to one variable to another variable then both belong to same list.

spy = [0,0,7]
agent = spy
spy[2]=8

so that's why you change spy so agent is also changed because both belong to the same list on same memory location. You can check that

id(spy)
id(agent)

that's call call by reference.

But if you assign the new list to spy after initialization of agent, then spy belongs to another list on another memory location.

id(spy)
id(agent)

You can also check this with the id() function which provides the reference ID of variable in memory.