How to copy an object?

  • copy.copy(x) Return a shallow copy of x.

  • copy.deepcopy(x[, memo]) Return a deep copy of x.

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

A=B

In [1]:
A=[1,2,3,4]
In [2]:
B=A
In [3]:
A.append(5)
In [4]:
A
Out[4]:
[1, 2, 3, 4, 5]
In [5]:
B
Out[5]:
[1, 2, 3, 4, 5]

B=copy.deepcopy(A)

B is indepdent with A

In [9]:
A=[1,2,3,4]
In [14]:
import copy

B=copy.deepcopy(A)
In [15]:
B
Out[15]:
[1, 2, 3, 4]
In [16]:
A.append(5)
In [17]:
A,B
Out[17]:
([1, 2, 3, 4, 5], [1, 2, 3, 4])
In [18]:
B.append(6)
In [19]:
A,B
Out[19]:
([1, 2, 3, 4, 5], [1, 2, 3, 4, 6])
In [24]:
A[0]='a'
A,B
Out[24]:
(['a', 2, 3, 4, 5], [1, 2, 3, 4, 6])
In [25]:
B[0]='A'
A,B
Out[25]:
(['a', 2, 3, 4, 5], ['A', 2, 3, 4, 6])

B=copy.copy(A)

In [20]:
A=[1,2,3,4]

C=copy.copy(A)
In [21]:
A,C
Out[21]:
([1, 2, 3, 4], [1, 2, 3, 4])
In [22]:
A.append(5)
A,C
Out[22]:
([1, 2, 3, 4, 5], [1, 2, 3, 4])
In [23]:
A[0]='a'
A,C
Out[23]:
(['a', 2, 3, 4, 5], [1, 2, 3, 4])
In [26]:
C[0]='A'
A,C
Out[26]:
(['a', 2, 3, 4, 5], ['A', 2, 3, 4])
In [27]:
C.append(6)
A,C
Out[27]:
(['a', 2, 3, 4, 5], ['A', 2, 3, 4, 6])

Comparison

In [28]:
A=[1,2,3,4]
B=copy.copy(A)
D=copy.deepcopy(A)
In [29]:
A,B,D
Out[29]:
([1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4])
In [30]:
A.append(5)
A,B,D
Out[30]:
([1, 2, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3, 4])
In [31]:
A[0]='a'
A,B,D
Out[31]:
(['a', 2, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3, 4])

so far, everyting is the same

In [35]:
A=[[1,2,3],['a','b','c']]

B=copy.copy(A)
D=copy.deepcopy(A)
E=A
In [36]:
A.append(['i','j','k'])
A,B,D,E
Out[36]:
([[1, 2, 3], ['a', 'b', 'c'], ['i', 'j', 'k']],
 [[1, 2, 3], ['a', 'b', 'c']],
 [[1, 2, 3], ['a', 'b', 'c']],
 [[1, 2, 3], ['a', 'b', 'c'], ['i', 'j', 'k']])
In [37]:
A[0][1]='II'
A,B,D,E
Out[37]:
([[1, 'II', 3], ['a', 'b', 'c'], ['i', 'j', 'k']],
 [[1, 'II', 3], ['a', 'b', 'c']],
 [[1, 2, 3], ['a', 'b', 'c']],
 [[1, 'II', 3], ['a', 'b', 'c'], ['i', 'j', 'k']])

The difference is shown up!