Shallow Copy [Python] — In Depth

--

In this article, you could find how shallow copy works in python, as well as depending on different data types the functionality of shallow copy changes.

Lets discuss different syntax that can be used to copy a list to another list. For instance, we need to copy a list List1 to List2 (regardless of its shallow or deep copy), we could use following formats.

List1= [1,2,3,[4,5]] # list with four elements

Equivalent memory diagram could be as referred as shown below:

list1 memory diagram
List1 is referring to four addresses, each of which could point to an element or any other address.

Syntax 1: Using Assignment Operator

List2 = List1

Syntax 2: Using List Slicing Operator

List2 = List1[:]

Syntax 3: Using List Type Casting

List2 = list(List1)

Syntax 4: Using copy()

List2 = List1.copy()

Syntax 5: Using copy.copy()

import copy

List2 = copy.copy(List1)

Syntax 6: Using copy.deepcopy()

import copy

List2 = copy.deepcopy(List1)

And many more….

After copy is done, the memory reference now be as shown below:

List2 had copied the reference of various elements of List1

A deep copy makes a new and separate copy of an entire object or list with its own unique memory address. What this means is that any changes you make in the new copy of the object/list won’t reflect in the original one.

A shallow copy also makes a separate new object object or list, but instead of copying the child elements to the new object, it simply copies the references to their memory addresses. Hence, if you make a change in the original object, it would reflect in the copied object, and vice versa.

But at times we can’t see shallow copy working as required for lists/nested lists. For instance, after copy of List1 to List2, if we change an element in List1 the similar effect can’t be seen in List2 and vice-versa. Refer explanation with code and diagram to understand the issue and reason behind that.

Reason is memory allocation goes differently in this case.

Change in linkage of List1 for fourth element whereas no change for List2
Change in linkage of List1 as well as List2 for element[3][0]

Similar, would be case of change in List2 would effect changes in List1 basis of their memory allocation.

You could also find and compare element addresses using id(object) function.

Thanks for reading!

--

--

Smriti Changulani
Python Data Wrangling by Smriti Changulani

Past — Software Engineer. Present — Data Analyst. Future — Data Scientist