jump to navigation

Python memory management 101 July 12, 2010

Posted by CK in Software.
Tags: ,
trackback

>>> 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

Comments»

No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: