[Tutor] Copying lists of lists
Norman Charnley
norman@earth.ox.ac.uk
Tue, 10 Oct 2000 09:19:26 +0100 (BST)
As the subject line says, I want to make a copy of a list of lists, but
I've encountered a problem which I can't understand.
First the obvious:
>>> a=[1,2,3]
>>> b=a[:]
>>> b[0]=99
>>> print a,b
>>> [1, 2, 3] [99, 2, 3]
OK, so far, so good. But:
>>> a=[[1,2,3],[4,5,6],[7,8,9]]
>>> b=a[:]
>>> b[0][0]=99
>>> print a
[[99, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> print b
[[99, 2, 3], [4, 5, 6], [7, 8, 9]]
i.e. a is reflecting the change made in b.
However, the following does work as I expected:
>>> a=[[1,2,3],[4,5,6],[7,8,9]]
>>> b=a[:]
>>> b[0]=99
>>> print a
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> print b
[99, [4, 5, 6], [7, 8, 9]]
Help, I'm a little confused, and I'd be grateful for an explanation. If
this were C I'd think it was a pointer problem...!
Many thanks,
Norman
=================================================
Dr. Norman Charnley
Department of Earth Sciences
University of Oxford
Oxford OX1 3PR, UK.
==================================================