a=b change b a==b true??

Chris Mellon arkanes at gmail.com
Mon Feb 26 09:00:12 EST 2007


On 26 Feb 2007 05:50:24 -0800, rstupplebeen at gmail.com
<rstupplebeen at gmail.com> wrote:
> I do not have a clue what is happening in the code below.
>
> >>> a=[[2,4],[9,3]]
> >>> b=a
> >>> [map(list.sort,b)]
> [[None, None]]
> >>> b
> [[2, 4], [3, 9]]
> >>> a
> [[2, 4], [3, 9]]
>
> I want to make a copy of matrix a and then make changes to the
> matrices separately.  I assume that I am missing a fundamental
> concept.  Any help would be appreciated.
>

this:
>>> b=a

does not make a copy. It binds the name b to the same object that is
bound to the name a. If you want a copy, ask for a copy.

>>> a = [1,2]
>>> import copy
>>> b = copy.copy(a) #shallow copy
>>> a.append(3)
>>> a,b
([1, 2, 3], [1, 2])
>>>


You may need to do something else depending on exactly what copy
semantics you want, read the docs on the copy module.



More information about the Python-list mailing list