Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #12923

Re: I am confused by

Date 2011-09-08 00:39 +0100
From MRAB <python@mrabarnett.plus.com>
Subject Re: I am confused by
References <CAO_vtCZt1CTZnN9ss-X3RM5a=09PhkS0sHo00H4g3soeAQkKFw@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.852.1315438747.27778.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: I am confused by MRAB <python@mrabarnett.plus.com> - 2011-09-08 00:39 +0100

csiph-web