简体   繁体   中英

Remove method in Python

I have the following code:

tree = {'nodes':[1,2,3],'root':[1]}
nodes = tree['nodes']
nodes.remove(2)
print(tree['nodes'])
print(nodes)

The output is the following:

[1, 3]
[1, 3]

My question may be stupid but I do not understand why remove method caused that tree variable has changed too?

I thought that when I create a new variable like nodes in the example above, then any method applied on this variable will affect only this variable.

From this example, I can conclude that it had an impact on a tree variable too.

Is it related to the global and local variables somehow?

Both nodes and tree['nodes'] are referring to the same block of memory. It means they are same. By changing any of them, both will be affected.

To avoid this, you can use copy .

from copy import copy

nodes = copy(tree['nodes'])

In this case, they are referring to different memory blocks so they are completely separated.

Also take a look at this link , it might be useful for better clue.

Its actually not a stupid question.

Most people like myself who have foundations built in languages like C++ have a little difficulty with this at first when you start learning Python , or even Java .

Unlike C++, in Python, everything is returned as a reference.

So even if you are accessing a part of the object via another variable, you still are accessing the same part of the object.

Read this to get more context around this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM