Python @ DjangoSpin

Python: Regular Assignment, Shallow copy & Deep Copy

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Regular Assignment, Shallow copy & Deep Copy in Python

Regular Assignment, Shallow copy & Deep Copy in Python

There are three ways to copy objects in Python: assignment, shallow copy & deep copy.

  1. Regular assignment points the new variable towards the original object. Let's use the builtin id() function to prove this. The id() function returns the object's memory address.
  2. objOne = [1, 2, 3]
    objTwo = [4, 5, 6]
    objThree = [objOne, objTwo]
    
    objFour = objThree
    
    print( id(objThree) == id(objFour) )			# True as objThree & objFour are the same object
    print( id(objThree[0]) == id(objFour[0]) )		# True as objThree[0] & objFour[0] are the same object
    
  3. Shallow copy

    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.

    Python Documentation

  4. import copy
    
    objFour = copy.copy(objThree)
    
    print( id(objThree) == id(objFour) )          # False as objFour is a new object
    print( id(objThree[0]) == id(objFour[0]) )    # True as objFour[0] is the same object as objThree[0]
    
  5. Deep Copy
  6. objFour = copy.deepcopy(objThree)
    
    print( id(objThree) == id(objFour) )          # False as objFour is a new object
    print( id(objThree[0]) == id(objFour[0]) )    # False as objFour[0] is a new object
    

    See also:

    Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply