• Direct assignment:It is essentially a reference (alias) to the object.

  • Shallow copy:Copies the parent object, but does not copy the internal child objects of the object.

  • Deep copy:The deepcopy method of the copy module fully copies the parent object and its child objects.

Dictionary Shallow Copy Example

Example

>>>a = {1: [1,2,3]} >>> b = a.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]})

Deep copy requires importing the copy module:

Example

>>>import copy >>> c = copy.deepcopy(a) >>> 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]})

Analysis

1、b = a: Assignment by reference — both a and b point to the same object.

2、b = a.copy():Shallow copy — a and b are independent objects, but their child objects still point to the same object (they are references).

b = copy.deepcopy(a):Deep copy — a and b fully copy the parent object and its child objects, and the two are completely independent.

More Examples

The following examples use copy.copy (shallow copy) and copy.deepcopy (deep copy) from the copy module:

Example

#!/usr/bin/python # -*-coding:utf-8 -*- import copy a = [1, 2, 3, 4, ['a', 'b']] # Original object b = a # Assignment, passes a reference to the object c = copy.copy(a) # Object copy, shallow copy d = copy.deepcopy(a) # Object copy, deep copy a.append(5) # Modify object a a[4].append('c') # Modify the ['a', 'b'] array object in object a print( 'a = ', a ) print( 'b = ', b ) print( 'c = ', c ) print( 'd = ', d )

The output of the above example is:

('a = ', [1, 2, 3, 4, ['a', 'b', 'c'], 5])
('b = ', [1, 2, 3, 4, ['a', 'b', 'c'], 5])
('c = ', [1, 2, 3, 4, ['a', 'b', 'c']])
('d = ', [1, 2, 3, 4, ['a', 'b']])