Shallow, Deep Copy and the twist of compound objects

#python #deep #shallow #copy

Soham Kundu Mar 17 2021 · 1 min read
Share this

Let's get straight to the point

Shallow Copy

  • References to the values are copied
  • We can use copy.copy() from copy module to achieve the same
  • Example
  •                     import copy

                        x=[1,[2,3],4]

                        y = copy.copy(x)

                        print("Pre Modification")

                        print(f"x is {x}")

                        print(f"y is {y}")

                        x[1][0]="Soham"

                        print("Post Modification")   

                        print(f"x is {x}")

                        print(f"y is {y}")

    Deep Copy

  • The value themselves are copied
  • The copy.deepcopy() from the copy module can be used for the same
  • Example
  •               x=[1,[2,3],4]

                  y=copy.deepcopy(x)

                  print("Pre Modification")

                  print(f"x is {x}")

                  print(f"y is {y}")

                  x[1][0]="Soham"   

                 print("Post Modification")

                 print(f"x is {x}") 

                 print(f"y is {y}")

    NOTE -

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

    - Official Python Documentation

    Example

  • Shallow Copy
  • x=[1,2,4]

    y = copy.copy(x)

    print("Pre Modification")

    print(f"x is {x}")

    print(f"y is {y}")

    x[1]="Soham"

    print("Post Modification")

    print(f"x is {x}")

    print(f"y is {y}")

  • Deep Copy
  • x=[1,2,4]

    y = copy.deepcopy(x)

    print("Pre Modification")

    print(f"x is {x}")

    print(f"y is {y}")

    x[1]="Soham"

    print("Post Modification")

    print(f"x is {x}")

    print(f"y is {y}")

    Hope it helps.

    Thanks

    Comments
    Read next