Deep Copy and Shallow Copy

Deep Copy and Shallow Copy

Date : 04/10/2019

copy module is used to create for shallow and deep copy operations Python.

Shallow copy=>create a new object and store the reference of original elements.

import copy
var1=[1,2,3,4]
var2=copy.copy(var1)
var1
[1, 2, 3, 4]
var2
[1, 2, 3, 4]

Example for Shallow copy using nested list:

var1=[[1,2],2,3]
var2=copy.copy(var1)
var1
[[1, 2], 2, 3]
var2
[[1, 2], 2, 3]
var2.append(30)
var2
[[1, 2], 2, 3, 30]
var1
[[1, 2], 2, 3]
var2[0][0]=90
var2
[[90, 2], 2, 3, 30]
var1
[[90, 2], 2, 3]

Deepcopy=>create the new object and add the nested objects and save the original elements.

Example for deep copy:

import copy
var1=[1,2,3,4]
var2=copy.deepcopy(var1)
var1
[1, 2, 3, 4]
var2
[1, 2, 3, 4]
var2.append(90)
var1
[1, 2, 3, 4]
var2
[1, 2, 3, 4, 90]

Example for deep copy using nested list:

import copy
var1=[[1,2],[2,3],[3,4]]
var2=copy.deepcopy(var1)
var1
[[1, 2], [2, 3], [3, 4]]
var2
[[1, 2], [2, 3], [3, 4]]
var2[0][0]=90
var2
[[90, 2], [2, 3], [3, 4]]
var1
[[1, 2], [2, 3], [3, 4]]

Thanks for using Pheonix solutions.

admin

Our team has expertise across software and web development, WordPress, e-commerce, mobile applications, UI/UX, cloud and infrastructure, DevOps, CI/CD, API integration, security, testing, automation, and technical support. The team also works with AI-based software solutions, LLMs, AI workflows, AI agents, and intelligent application development to help businesses automate processes and build smarter digital solutions. We focus on developing, deploying, maintaining, and optimising secure, scalable, and reliable technology solutions while helping businesses adopt modern technologies and drive digital transformation.

Leave a Reply

Scroll to Top