On 07/09/2011 23:57, Martin Rixham wrote:
Hi all
I would appreciate some help understanding something. Basically I am
confused by the following:
>>> a = [[0, 0], [0, 0]]
>>> b = list(a)
>>> b[0][0] = 1
>>> a
[[1, 0], [0, 0]]
I expected the last line to be
[[0, 0], [0, 0]]
I hope that's clear enough.
What you were expecting is called a "deep copy".
You should remember that a list doesn't contain objects themselves, but
only _references_ to objects.
"list" will copy the list itself (a "shallow copy"), including the
references which are in it, but it won't copy the _actual_ objects to
which they refer.
Try using the "deepcopy" function from the "copy" module:
>>> from copy import deepcopy
>>> a = [[0, 0], [0, 0]]
>>> b = deepcopy(a)
>>> b[0][0] = 1
>>> a
[[0, 0], [0, 0]]
--
http://mail.python.org/mailman/listinfo/python-list