Variables in Python are simply object names. If you change the object with any name attached to it, you will see the changes from any other name. Python never creates copies for you automatically, in particular:
someList.append(foo)
does not create a copy of foo and places it in someList , it adds an object to which the name foo refers.
You can create a middle name for this object.
bar = foo
but it also does not create a copy. In particular,
foo['x'] = 42
and
bar['x'] = 42
will work on exactly the same facility. You can verify this by typing the memory address of the object:
print id(foo), id(bar)
and make sure they are the same.
If you need a copy in Python, you will need to create it explicitly. Depending on what you need, the copy module - either copy.copy() or copy.deepcopy() - will do what you need:
import copy bar = copy.copy(foo) print id(foo), id(bar)
should now print different memory locations.
source share