Easy Tutorial
❮ Zookeeper Java Setup Python Basic Datatype ❯

Python Direct Assignment, Shallow Copy, and Deep Copy Analysis

Category Programming Technology

-

Direct Assignment: It is actually a reference (alias) to the object.

-

Shallow Copy (copy): Copies the parent object without copying the child objects within the object.

-

Deep Copy (deepcopy): The deepcopy method of the copy module completely 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 (it's a reference).

b = copy.deepcopy(a): Deep copy, a and b have completely copied the parent object and its child objects, both are completely independent.

More Examples

The following examples use the copy module's copy.copy (shallow copy) and (copy.deepcopy):

Example

#!/usr/bin/python
# -*-coding:utf-8 -*-

import copy
a = [1, 2, 3, 4, ['a', 'b']] #original object

b = a                       #assignment, passing the reference of 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']])
❮ Zookeeper Java Setup Python Basic Datatype ❯