A glance at python’s memory management

Just learned the hard way about some basics of python’s memory management. For people coming from R or other languages, it might be confusing to realize that if you define

x = [1,2,3]

set

x = y

and then modify x, for instance through

x.append(4)

the change in x will propagate to y. This means that if you query the value of y, you will in fact get

[1,2,3,4]

This also means that the sequence

x = [1,2,3]
x.append(4)

Is very much different from

x = [1,2,3,4]

For more on this and how to “really” define a new list with some life of its own in the memory, but with the same value as x, see http://henry.precheur.org/python/copy_list.

Advertisements