List transfer to another list

Is there a reason why assigning a list to another list and changing an item in one reflects a change in both, but changing the entire list of one does not reflect a 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
source share
3 answers

Your first mutates the object, the second renames the name.

( listwhich contains spy)[2]=8

(the name is called "spy") = "hello"

+7
source

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

Follow this:

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

'a', 5, 'b' 'a', 5. 'a' 3. 'b' 5 'a' - .

spy = [0,0,7]

"" , [0, 0, 7]

agent = spy

"" , [0, 0, 7]

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

2 8. - , . ​​

spy = [0,0,7]

"" [0, 0, 7]

agent = spy

"" [0, 0, 7]

spy = "hello"

"" , "". "" .

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

?

+2

When you assign a list of one variable to another variable, both belong to the same list.

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

so you change the spy, so the agent also changes because both belong to the same list in the same memory location. You can check that

id(spy)
id(agent)

which cause a call by reference.

But if you assign a new list to the spy after initializing the agent, then the spy belongs to another list in a different memory location.

id(spy)
id(agent)

You can also check this with the id () function, which provides a reference identifier for a variable in memory.

+1
source

All Articles