Newbie, problem array

Simon Brunning SBrunning at trisystems.co.uk
Wed Apr 11 11:22:27 EDT 2001


> From:	Roland Oviol [SMTP:roviol at venmex.com]
> Sent:	Wednesday, April 11, 2001 3:49 PM
> To:	python-list at python.org
> Subject:	Newbie, problem array
> 
> hello,
> 
> It's the problem
> 
> >>>d1=[[0,0]]
> >>>d2=d1   #reference no copy
> >>>d2[0][0]=3
> >>>d2
> [[3,0]]
> >>>d1
> [[3,0]]
> 
> ok
> 
> but,
> >>>d1=[[0,0]]
> >>>d2=d1[:]    #copy, no reference
 
> >>>d2[0][0]=3
> >>>d2
> [[3,0]]
> >>>d1
> [[3,0]]
> 
> Why, is copy, no reference
> 
> How copy a object?
 
d2 contains a *copy* of the list contained in d1, yes, rather than
containing another reference to the same list. But the list referred to by
d1 contains a *reference* to another list. The list referred to by d2
contains another reference to the same inner list.

Basically, you performed a *shallow* copy, i.e. copied the object, and
copied the references contained within it. If you want to copy the object,
and to copy the *objects* within it, you want to take a *deep* copy:

import copy
d2 = copy.deepcopy(d1)

Cheers,
Simon Brunning
TriSystems Ltd.
sbrunning at trisystems.co.uk




-----------------------------------------------------------------------
The information in this email is confidential and may be legally privileged.
It is intended solely for the addressee. Access to this email by anyone else
is unauthorised. If you are not the intended recipient, any disclosure,
copying, distribution, or any action taken or omitted to be taken in
reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot
accept liability for statements made which are clearly the senders own.




More information about the Python-list mailing list