List behaviour

Diez B. Roggisch deets at nospam.web.de
Wed May 17 11:18:11 EDT 2006


barberomarcelo at gmail.com wrote:

> Maybe I'm missing something but the latter is not the behaviour I'm
> expecting:
> 
>>>> a = [[1,2,3,4], [5,6,7,8]]
>>>> b = a[:]
>>>> b
> [[1, 2, 3, 4], [5, 6, 7, 8]]
>>>> a == b
> True
>>>> a is b
> False
>>>> for i in range(len(b)):
> ...     for x in range(4):
> ...         b[i][x] = b[i][x] + 10
> ...
>>>> b
> [[11, 12, 13, 14], [15, 16, 17, 18]]
>>>> a
> [[11, 12, 13, 14], [15, 16, 17, 18]]
>>>>

b = a[:]

does clone a, but doesn't make a deepcopy of its contents, which you are
manipulating! 

So do
[GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
poWelcome to rlcompleter2 0.96
for nice experiences hit <tab> multiple times
>>> import copy
>>> a = [[10]]
>>> b = copy.deepcopy(a)
>>> b[0][0] = 20
>>> a
[[10]]
>>> b
[[20]]
>>>            


HTH,

Diez



More information about the Python-list mailing list