[Tutor] Deep Copy
Kirby Urner
urnerk@qwest.net
Mon, 15 Apr 2002 21:30:37 -0700
>But, I would prefer not doing that every time (I am doing this alot).
>
> - Tim
Fastest way to copy a list is:
newlist = oldlist[:]
That's a shallow copy, which is sufficient for the example
you gave, e.g. a list of integers or strings.
However, if oldlist contains objects and you want clones
of those objects as well, then you need the deepcopy
function in the copy module.
Here's some illustrative shell interaction:
>>> class Foo:
def __init__(self,var):
self.value = var
>>> o1 = Foo(2)
>>> o2 = Foo(3)
>>> oldlist = [o1,o2]
>>> newlist = oldlist[:]
>>> id(oldlist)
11363440
>>> id(newlist) # ok, two distinct lists
11371104
>>> o1.value = 4
>>> newlist[0].value # oh oh, object o1 is same in both
4
>>> import copy # copy to the rescue!
>>> newlist = copy.deepcopy(oldlist)
>>> o1.value = 44 # change o1's value property again
>>> oldlist[0].value # old list is effected
44
>>> newlist[0].value # newlist has clone of o1, unchanged
4
>>> id(newlist[0])
11406848
>>> id(oldlist[0]) # confirming the difference
11347248
Kirby