[Tutor] Copying lists of lists

alan.gauld@bt.com alan.gauld@bt.com
Tue, 10 Oct 2000 17:21:59 +0100


> OK, so far, so good. But:
> >>> a=[[1,2,3],[4,5,6],[7,8,9]]
> >>> b=a[:]
> >>> b[0][0]=99
> 
> However, the following does work as I expected:
> >>> a=[[1,2,3],[4,5,6],[7,8,9]]
> >>> b=a[:]
> >>> b[0]=99

> If this were C I'd think it was a pointer problem...!

It is a pointer problem.
In python all variables are references(aka pointers) to the data.
Thus a is a 'pointer' to a list of 'pointers' to sub lists.

When you change b[0] you actually change what b[0] points at 
whereas when you change b[0][0] the b[0] pointer stays the same
(ie the value shared with a[0]).

You need to do a deepcopy of the lists to avoid this completely.
(I think I saw a deepcopy function or module somewhere, if not 
 it's fairly easy to write - esecially if you use recursion)

Alan G.