Duplicated List...

David Porter jcm at bigskytel.com
Tue Dec 26 11:09:03 CET 2000


* dyo <dyo at shinbiro.com>:

> >>> a=[1,2,3]
> >>> b=[a,10,20,30]
> >>> b[0].append('x')
> >>> b
> [[1, 2, 3, 1, 2, 3, 'x'], 10, 20, 30]
> >>> a
> [1, 2, 3, 1, 2, 3, 'x']
> >>> a.append('xxx')
> >>> a
> [1, 2, 3, 1, 2, 3, 'x', 'xxx']
> >>> b
> [[1, 2, 3, 1, 2, 3, 'x', 'xxx'], 10, 20, 30]

a and b[0] are references to the same object (try id() to test this).
So in both cases you are altering in place the same object. Since both a and
b[0] point to the same object they are both altered.

> But in this case..
> 
> >>> a=[1,1000]
> >>> a
> [1, 1000]
> >>> b
> [[1, 2, 3, 1, 2, 3, 'x', 'xxx'], 10, 20, 30]
> >>>
> 
> Why do not change List 'b' ?
> What happen List 'b' ?

You did not alter a in place this time. A new object was created with a
pointing to it. b[0] still points to the old object. Since we know from
above that altering in place will not create a new object, you can do this
instead:

>>> a[:]=[1,1000] 
>>> a
[1, 1000]
>>> b
[[1, 1000], 10, 20, 30]


David





More information about the Python-list mailing list