Custom Search

Tuesday, September 21, 2010

python shallow and deepcopy examples


>>> import copy

>>> dir(copy)
['Error', 'PyStringMap', '_EmptyClass', '__all__', '__builtins__', '__doc__',
'__file__', '__name__', '_copy_dispatch', '_copy_immutable', '_copy_inst',
'_copy_with_constructor', '_copy_with_copy_method', '_deepcopy_atomic',
'_deepcopy_dict', '_deepcopy_dispatch', '_deepcopy_inst', '_deepcopy_list', '
_deepcopy_tuple', '_getspecial', '_keep_alive', '_reconstruct', '_test', 'copy', '
deepcopy', 'dispatch_table', 'error', 'inspect', 'name', 't']




>>> a = [[3,4],[1,2]]

>>> def test(k):
... for x in k:
... x.append(8)
...

>>> test(a)
>>> a
[[3, 4, 8], [1, 2, 8]]

-------------------------a[:] --->shallow copy
>>> a = [[3,4],[1,2]]
>>> a
[[3, 4], [1, 2]]
>>> test(a[:])
>>> a
[[3, 4, 8], [1, 2, 8]]

-------------------------copy.copy() --->shallow copy
>>> a = [[3,4],[1,2]]
>>> a
[[3, 4], [1, 2]]
>>> test(copy.copy(a))
>>> a
[[3, 4, 8], [1, 2, 8]]

-------------------------copy.deepcopy() ---> deep copy
>>> a = [[3,4],[1,2]]
>>> a
[[3, 4], [1, 2]]
>>> test(copy.deepcopy(a))
>>> a
[[3, 4], [1, 2]]
>>>

=======================

>>> a = [1,2,3,4]
>>> def test(k):
... k.append(8)
...
>>> test(a)
>>> a
[1, 2, 3, 4, 8]


>>> a = [1,2,3,4]
>>> test(a[:]) --->shallow copy
>>> a
[1, 2, 3, 4]


>>> a = [1,2,3,4]
>>> test(copy.copy(a)) --->shallow copy
>>> a
[1, 2, 3, 4]


>>> a = [1,2,3,4]
>>> test(copy.deepcopy(a)) ---> deep copy
>>> a
[1, 2, 3, 4]
>>>

========================

Shallow copies of dictionaries can be made using dict.copy(), and of lists by
assigning a slice of the entire list, for example, copied_list = original_list[:].

No comments:

Post a Comment