Peer uest
Contact Help
Home
 

In Python, when you use = to assign an object to a variable, it will simply point the new variable towards the existing object. 

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

  1. 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.
  2. A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

Shallow copy example

x = ['a', 'b', 'c']
y = x
y.append('d')
print('x = ', x)
print('y = ', y)
print('x_id = ', id(x))
print('y_id = ', id(y))

The output is

x =  ['a', 'b', 'c', 'd']
y =  ['a', 'b', 'c', 'd']
x_id =  4535422880
y_id =  4535422880

Deep copy example

import copy
x = ['a', 'b', 'c']
y = copy.deepcopy(x)
y.append('d')
print('x = ', x)
print('y = ', y)
print('x_id = ', id(x))
print('y_id = ', id(y))

output

x =  ['a', 'b', 'c']
y =  ['a', 'b', 'c', 'd']
x_id =  4535320736
y_id =  4530058656

 

Add a Comment
×
×
×