3

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]
asked Apr 21, 2012 at 21:14

3 Answers 3

7

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

(list that spy contains)[2]=8

(name called "spy")= "hello"

answered Apr 21, 2012 at 21:16
0
2

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?

answered Apr 21, 2012 at 21:30
1
  • @downvoter, any constructive comments on how my answer can be improved? Commented Apr 27, 2012 at 18:33
1

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.

Saulo Silva
1,2862 gold badges24 silver badges38 bronze badges
answered Oct 1, 2012 at 11:21

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.