jump to navigation

Python memory management 101 July 12, 2010

Posted by CK in Software.
Tags: ,
add a comment

>>> a = 1
>>> b = a
>>> b += 1
>>> b
2
>>> a
1
>>>

…but:

>>> a = []
>>> b = a
>>> b.append(1)
>>> b
[1]
>>> a
[1]
>>>

Same for custom classes/objects.

Technically it makes sense, of course, to avoid deep-copying. On the other hand, it may be counter-intuitive in cases like this:

>>> a = 2 * [[]]
>>> a
[[], []]
>>> a[0].append(1)
>>> a
[[1], [1]]
>>>

It took me a minute to recover and realize, that statement a = 2 * [[]] does not create 2 different lists within “a”, but rather 2 references to the same list.

Advertisements