0%

Shallow and Deep Copy in Python

Assignment, Shallow Copy (Copy) and Deep Copy

  • Assignment: Just add one more reference to the origin object
  • Shallow Copy: Or just Copy, which will just copy top level object, but will not copy sub-level object (add one more reference for sub-level object)
  • Deep Copy: Completely copy the whole object

Example using dictionary

1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>>import copy
>>>a = {1: [1,2,3]}
>>>b = a.copy() # Shallow Copy
>>>a, b
>>>({1: [1,2,3]},{1: [1,2,3]})
>>>a[1].append(4)
>>>a, b
>>>({1: [1,2,3,4]},{1:[1,2,3,4]})
>>>c = copy.deepcopy(a) # deep copy
>>>a, c
>>>({1: [1,2,3,4]},{1:[1,2,3,4]})
>>>a[1].append(5)
>>>a, c
>>>({1: [1,2,3,4,5]},{1: [1,2,3,4]})

Explanation

  1. b=a: assignment, a and b will point to the same object
    • -w427
  2. b=a.copy(): shallow copy, a and b are independent object, however, their sub-objects still point to the same object.
    • -w454
  3. b=a.deepcopy(): deep copy, a and b are totally independent object, at any level.
    • -w489
Thanks for Your Supports.