References vs copies w/ *x

Emile van Sebille emile at fenx.com
Fri Oct 1 07:49:30 EDT 1999


Brian,

>>> a = [1,2,3]
>>> b = [[]]*3
>>> b = map(lambda x:a[:],b)
>>> b[1][1] = 'c'
>>> b
[[1, 2, 3], [1, 'c', 3], [1, 2, 3]]

-----or-----

>>> a = [1,2,3]
>>> b = []
>>> for i in range(3):b.append(a[:])
>>> b[1][1] = 'c'
>>> b
[[1, 2, 3], [1, 'c', 3], [1, 2, 3]]

--

Emile van Sebille
emile at fenx.com
-------------------


Zamboo <despamme.bstankie at eye.psych.umn.edu> wrote in message
news:despamme.bstankie-0110990212010001 at pub56k-29-72.dialup.umn.edu...
> Hello,
>
> I have read through the Learning Python book and have found some
peculiar
> behavior with the *x (repetition) command.  Here is what I am doing
and
> getting:
>
> >>> a=[1,2,3]
> >>> b=[a[:]]*3
> >>> b
> [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
> >>> b[0][2]=10
> >>> b
> [[1, 2, 10], [1, 2, 10], [1, 2, 10]]
>
>
> Notice that if I change one of the elements in b, it changes all of
the
> elements.  I assume that the repetition is also referencing a memory
> location, but how can I force the repetition command to make copies?
>
> Thanks,
> Brian
>
> --
> <if you want to e-mail me please de-spam my address>






More information about the Python-list mailing list