I am confused by

Gary Herron gherron at digipen.edu
Thu Sep 8 01:31:37 CEST 2011


On 09/07/2011 03:57 PM, 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.
>
> Martin

You were expecting the assignment to "b" to create a copy of the 
original list, and it does, but the copy is only one level deep.

So a and b are different lists, but a[i] and b[i] are the same objects 
for each i.

There is a "deepcopy" in the library which may do what you expect.

Gary Herron


-- 
Gary Herron, PhD.
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418




More information about the Python-list mailing list