Shallow Copy

Shallow copy in Python allows to create copy of objects. With shallow copy the object references to the same memory and shares the value across the objects.

See example below different ways to shallow copy objects.

Assign object to other object with “=” operator.

Performance: this approach is fastest as comapred to [:] and deep copy

Assign object to other object with [:]. This creates a new reference to the memory allocated for the list.

Performance: this approach is slower than the “=” operator as it creates a new reference.

Deep Copy

Deep copy creates a new instance of the object and allocates different memory location and the values associated are different from the copied/source object.

Below example uses deepcopy() method from the copy package.

Performance: This approach has a comprehensive operation and slower the above 2 approaches.

Deep copy wont call the constructor and copies the data with the new memory chunk.