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


Groups > comp.lang.python > #12923 > unrolled thread

Re: I am confused by

Started byMRAB <python@mrabarnett.plus.com>
First post2011-09-08 00:39 +0100
Last post2011-09-08 00:39 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

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

#12923 — Re: I am confused by

FromMRAB <python@mrabarnett.plus.com>
Date2011-09-08 00:39 +0100
SubjectRe: I am confused by
Message-ID<mailman.852.1315438747.27778.python-list@python.org>
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]]

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web