2

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?

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
John Snow
  • 107
  • 1
  • 10
  • Let's change the terminology. You don't create a new variable `nodes`, you just attach another label `nodes` to `tree['nodes']`. – Matthias Nov 11 '20 at 12:19

2 Answers2

6

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.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
0

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.

Serial Lazer
  • 1,667
  • 1
  • 7
  • 15