Copying in programming

Deep copy

A full or deep copy is a separate object with the same values as the original, but no longer connected to it in any way

Suppose there is an object A

A = [1, 2, 3]

If we make a deep copy A → B

A = B = [1, 2, 3]

The objects are equal, but if we change the values in A it will not affect B in any way

A[0] = 4
A[1] = 5
A[2] = 6

A = [4, 5, 6]

B = [1, 2, 3]

B used to be a copy of A, and now the values do not match, and that is normal

Shallow copy

An incomplete or shallow copy of an object

Let us consider object A again

A = [4, 5, 6]

If we make a shallow copy A → C

C = [4, 5, 6]

C is equal to A, and if we now change the value of A the value of C will change too, because a shallow copy has no elements of its own, it simply points to the elements of A

A[0] = 7
A[1] = 8
A[2] = 9

A = [7, 8, 9]
C = [7, 8, 9]

Article author: Andrei Olegovich