Deep Copy in python – Modify Copied list without changing original list
Hi, today we will learn about Deep Copy in python. It is a very important topic if we work with mutable objects. Python is a very smart and advanced programming language. It uses dynamic memory allocation technique. Python uses a private heap data structure to store its program variables data.
List copy problem in python: Deep Copy
In Python, we can find a problem with copying any mutable objects value to another. If we use ‘=’ sign to store the data of the mutable object into another variable. After copying if we change the copied variable data then the original mutable objects data also are affected.
In this example, we can see how the original list is affected by copied list operations.
list_org = [1,2,3,4,5,6] # Original List list_cpy = list_org # Copying the Original List list_cpy = 10 # Set the first element as 10 of the copy list print('Copy List :',list_cpy) # Printing the whole copy list print('Original List :',list_org) # Printing the whole Original list
Copy List : [10, 2, 3, 4, 5, 6] Original List : [10, 2, 3, 4, 5, 6]
Here we can find a problem. We changed the first value on ‘list_cpy’ list but in the output, both lists are the same. If we simply use ‘=’ to copy the whole ‘list_org’ to ‘list_cpy’ then any changes on ‘list_cpy’ will affect the ‘list_org’.
To overcome this we will use the Copy library. And copy.deepcopy() function.
Modify a copied list without changing the original list in Python using deep copy
import copy list_org = [1,2,3,4,5,6] # Original List list_cpy = copy.deepcopy(list_org) # Deep Copy the Original List list_cpy = 10 # Set the first element as 10 of the copy list print('Copy List :',list_cpy) # Printing the whole copy list print('Original List :',list_org) # Printing the whole Original list
Copy List : [10, 2, 3, 4, 5, 6] Original List : [1, 2, 3, 4, 5, 6]
In this output, we can get our desired output. In this program, we changed the first value of ‘list_cpy’. And we get the output as expected. Here ‘list_cpy’ value is changed but the value of ‘list_org’ is unchanged.
The Python language uses dynamic memory allocation technique. Python does not allocate extra memory address for storing the copied data of any mutable objects.
Python allocates the memory reference as their value. So, any further modification can affect the original data.
To overcome this problem python has introduced the ‘Copy’ library and deepcopy() function. Deepcopy doesn’t store any memory reference as any copied value. Deepcopy store the actual value of the data as their copied value. So there is no chance of memory reference problem. Now we can modify any copied object without hampering the original object.
You may like to read:
- Introduction to Linked Lists and How to implement in Python
- Print Each Character of a String one at a time in Python