[Tutor] about copy.copy
Kent Johnson
kent37 at tds.net
Tue Jul 18 12:07:18 CEST 2006
Luke Paireepinart wrote:
> linda.s wrote:
>
>> what is the difference between b and c in the following code?
>>
> #---copyexample.py
> import copy
> a=[1,4,5]
> b=a
> c=copy.copy(a)
>
> del(a[0])
> print a
> print b
> print c
>
> #---eof
>
> output:
> [4, 5]
> [4, 5]
> [1, 4, 5]
>
>
> I.E. 'b' is just a reference to 'a', so modifying 'a' by deleting an
> element changed the value of 'b' (since they are really both just
> references to the
> same data structure in memory.)
>
Assignment makes a new reference to the same object. When you say
b = a
b and a now refer to the same object, in this case a list. Another way
to say this is, a and b are aliases of the same object. If the object is
mutable (can be changed), then any change to the object through either
reference is equivalent.
Note that some objects, like ints and strings, are immutable - they
can't be changed. If you say
a = 1
b = a
a = a + 1
you are actually making a refer to a new integer with the value two, so
b doesn't change.
When you use copy.copy(), you create a /shallow copy/ of a. A shallow
copy only copies one level deep. So when a is a list, a shallow copy
makes a new list populated with references to the same objects as
contained in the original list.
This is a situation very similar to a=b, except it is pushed down one
level. If the list elements themselves are mutable then changes to the
elements in one list will be reflected in the other list. In your case,
you made a list of lists. Copying with copy.copy() makes a new list
whose elements are references to the same lists as contained in the
original list. Changing one of the elements is reflected in both lists.
Try copy.deepcopy() if you want to make copies all the way down.
This article might help you understand the semantics of assignment in
Python:
http://effbot.org/zone/python-objects.htm
Kent
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
More information about the Tutor
mailing list