Research breakthrough possible @S-Logix pro@slogix.in

Office Address

Social List

How to do Shallow Copy and Deep Copy in Python?

Shallow Copy and Deep Copy in Python

Condition for Shallow Copy and Deep Copy in Python

  • Description:
    Shallow copy is used when you need a new object, but sharing nested objects is acceptable.
    Deep copy is used when you need a completely independent copy, including nested objects.
Step-by-Step Process
  • Shallow copy:
    Create a new object that is a copy of the original object.
    Copy references to the objects contained in the original, not the actual objects.
    Nested objects (such as lists within a list) are shared between the original and the copied object.
    Modify the shallow copys nested objects, and it will affect the original object as well.
  • Deep copy:
    Create a new object that is a copy of the original.
    Recursively copy all objects contained in the original object, including nested objects.
    Nested objects are fully copied, so modifying the deep copy will not affect the original object.
Sample Code
  • #Shallow copy
    import copy
    print("Output for shallow copy:")
    original_list = [1, [2, 3], 4]
    shallow_copy = copy.copy(original_list)
    shallow_copy[1][0] = 99
    print("Original List:", original_list)
    print("Shallow Copy:", shallow_copy)
    print()
    #Deep copy
    import copy
    print("Output for deep copy:")
    original_list = [1, [2, 3], 4]
    deep_copy = copy.deepcopy(original_list)
    deep_copy[1][0] = 99
    print("Original List:", original_list)
    print("Deep Copy:", deep_copy)
Screenshots
  •  Shallow Copy and Deep Copy