SlideShare a Scribd company logo
1 of 25
Download to read offline
Shallow Copy and Deep Copy
CHAPTER – 4
THE BASICS OF SEARCH ENGINE FRIENDLY DESIGN & DEVELOPMENT
Copyright @ 2019 Learntek. All Rights Reserved. 3
Shallow Copy and Deep Copy
In Python programming, many times we need to make a copy of variable(s). In
orders to make copy different methods are available in the Python
programming. Let’s take the example of the integer.
>>> a = 10
>>> b = 10
>>> id(a)
140730625348928
>>> id(b)
140730625348928
>>>
>>> x = 257
>>> y = 257
>>> id(x)
2067355160528
>>> id(y)
2067355160432
>>>
Copyright @ 2019 Learntek. All Rights Reserved.
4
If an integer value is less than 256 then interpreter doesn’t make the copy, for a = 10
and b= 10 both the variables are referring to same memory allocation. But if the
value exceeds the 256 then interpreter make a separate copy for each variable. See
the figure below for more clarification
Copyright @ 2019 Learntek. All Rights Reserved. 5
Let us take the example of Python list.
See the following example
>>> list1 = [1,2,3]
>>> list2 = [1,2,3]
>>> id(list1)
2067355168648
>>> id(list2)
2067353438600
>>>
Copyright @ 2019 Learntek. All Rights Reserved. 6
Addresses of both the lists are different. Let us create the copy of one variable
>>> list1 = [1,2,3]
>>> list3 = list1
>>> >>> id(list1)
2067355168648
>>> id(list3)
2067355168648
Copyright @ 2019 Learntek. All Rights Reserved. 7
It means both the variable are referring to same object or list.
Let see the different methods to create the copy of variable which refers to a list.
Copyright @ 2019 Learntek. All Rights Reserved. 8
First method
>>> list4 = list1[:]
>>> list4
[1, 2, 3]
>>> id(list4)
2067355181192
>>> id(list1)
2067355168648
>>>
Copyright @ 2019 Learntek. All Rights Reserved. 9
Second method
>>>
>>> list5 = list(list1)
>>> >>> id(list5)
2067355181640
>>>
>>> id(list1)
2067355168648
>>>
You can check the addresses of list1 and list4, list1 and list5 are different.
Copyright @ 2019 Learntek. All Rights Reserved. 10
Let us see one more example. >>> list1 = [1,2,["a","b"]]
>>>
>>> list2 = list1[:]
>>> list2
[1, 2, ['a', 'b’]]
>>> id(list2)
2067355167944
>>> id(list1)
2067355168136
>>>
Copyright @ 2019 Learntek. All Rights Reserved. 11
Up to this level, nothing is surprising. Both the Python copy lists depicting different
Python lists. >>> list1[2]
['a', 'b’]
>>> id(list1[2])
2067323314824
>>>
>>> id(list2[2])
2067323314824
>>>
>>> list2[2] ['a', 'b’]
>>>
Copyright @ 2019 Learntek. All Rights Reserved. 12
The above code is very surprising. It means list1 and list2 contain the same sub-list.
Copyright @ 2019 Learntek. All Rights Reserved. 13
This type of copy is called shallow copy. The inner sub-list address is same for the
list1 and list2.
Let us append the inner sub-list.
>>> list1 = [1,2,["a","b"]]
>>> list2 = list1
>>>
>>> list2 = list1[:]
>>> list2
[1, 2, ['a', 'b’]]
[
>>> list1
Copyright @ 2019 Learntek. All Rights Reserved. 14
[1, 2, ['a', 'b’]]
>>>
>>> list1[2].append('c’)
>>> list1
[1, 2, ['a', 'b', 'c’]]
>>> list2
[1, 2, ['a', 'b', 'c’]]
>>>
You can see if the sub-list list1[2] is updated then the impact also reflected to the
list2[2].
Copyright @ 2019 Learntek. All Rights Reserved. 15
Learn Python + Advanced Python Training
If you use syntax list2 = list(list1) then this syntax would give you the same answer.
Copyright @ 2019 Learntek. All Rights Reserved. 16
Deep Copy
Now, what is the solution of shallow copy problem? The solution is a deep copy
which allows a complete copy of the list. In other words, It means first
constructing a new collection object and then recursively populating it with
copies of the child objects found in the original.
Fortunately, in Python, we have copy module to accomplish the task.
See the following series of commands
Copyright @ 2019 Learntek. All Rights Reserved.
17
>>> list1 = [1,2,["a","b"]]
>>> from copy import deepcopy
>>> list2 = deepcopy(list1)
>>> id(list1)
1724712551368
>>> id(list2)
1724744113928
>>>
>>> id(list1[2])
1724712051336
>>> id(list2[2])
1724713319304
Copyright @ 2019 Learntek. All Rights Reserved. 18
You can see in both the Python list, list1 and list2, the sub-list is at different addresses.
>>> list2[2] ['a', 'b’]
>>> list2[2].append("c")
>>> list2 [1, 2, ['a', 'b', 'c’]]
>>>
>>> list1 [1, 2, ['a', 'b’]]
>>>
If we append something in the sub-list of list2 then it does not reflect on the sub-list
of list1.
Let us take a complex example
Copyright @ 2019 Learntek. All Rights Reserved. 19
>>> list1 = [1,2,("a","b",[1,2],3),4]
>>> list1
[1, 2, ('a', 'b', [1, 2], 3), 4]
>>> import copy
>>> list2 = copy.deepcopy(list1)
>>> list2
[1, 2, ('a', 'b', [1, 2], 3), 4]
>>> list1[2][2] [1, 2]
>>> list1[2][2].append(5)
>>> list1
[1, 2, ('a', 'b', [1, 2, 5], 3), 4]
>>> list2
[1, 2, ('a', 'b', [1, 2], 3), 4]
>>>
Copyright @ 2019 Learntek. All Rights Reserved. 20
We can say the deep copy is working fine.
Let us take the case of Dictionary. In the dictionary, with the help of method copy, we
can produce a copy of the dictionary. Let us see an example.
>>> dict1 = {1: 'a', 2: 'b', 3: ['C', 'D’]}
>>>
>>> dict2 = dict1.copy()
>>>
>>> dict2[3] ['C', 'D’]
>>>
>>> dict2 {1: 'a', 2: 'b', 3: ['C', 'D’]}
>>>
Copyright @ 2019 Learntek. All Rights Reserved. 21
>>> dict2[3].append("E")
>>> dict2
{1: 'a', 2: 'b', 3: ['C', 'D', 'E’]}
>>> dict1
{1: 'a', 2: 'b', 3: ['C', 'D', 'E’]}
>>> >
>> id(dict1[3])
1724744113864
>>>
>>> id(dict2[3])
1724744113864
>>>
Copyright @ 2019 Learntek. All Rights Reserved. 22
So, what above series of command infers. See the following diagram.
Copyright @ 2019 Learntek. All Rights Reserved. 23
It means the dict method copy also produce the shallow copy.
Let take the help of deep copy to produce to a deep copy.
>>> dict3 = deepcopy(dict1)
>>> dict3
{1: 'a', 2: 'b', 3: ['C', 'D', 'E’]}
>>> dict1[3].append("L")
>>>
>>> dict1
{1: 'a', 2: 'b', 3: ['C', 'D', 'E', 'L’]}
>>>
>>> dict3
{1: 'a', 2: 'b', 3: ['C', 'D', 'E’]}
>>>
Copyright @ 2019 Learntek. All Rights Reserved. 24
Means changes of dict1 are not reflecting dict3.
In the end we can conclude that
Making a shallow copy of an object won’t clone internal objects. Therefore, the
copy is not fully independent of the original.
A deep copy of an object will recursively clone internal objects. The clone is fully
independent of the original, but creating a python deep copy is slower.
Copyright @ 2019 Learntek. All Rights Reserved. 25
For more Training Information , Contact Us
Email : info@learntek.org
USA : +1734 418 2465
INDIA : +40 4018 1306
+7799713624

More Related Content

What's hot

Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring FrameworkASG
 
Spring: Overview do framework mais popular para desenvolvimento em Java
Spring: Overview do framework mais popular para desenvolvimento em JavaSpring: Overview do framework mais popular para desenvolvimento em Java
Spring: Overview do framework mais popular para desenvolvimento em JavaMariana de Azevedo Santos
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVCIndicThreads
 
Spring Framework - Validation
Spring Framework - ValidationSpring Framework - Validation
Spring Framework - ValidationDzmitry Naskou
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and ConcurrencyRajesh Ananda Kumar
 
Angular 4 and TypeScript
Angular 4 and TypeScriptAngular 4 and TypeScript
Angular 4 and TypeScriptAhmed El-Kady
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooksSamundra khatri
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsYura Nosenko
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ Ganesh Samarthyam
 
Angular directives and pipes
Angular directives and pipesAngular directives and pipes
Angular directives and pipesKnoldus Inc.
 
Angular Pipes Workshop
Angular Pipes WorkshopAngular Pipes Workshop
Angular Pipes WorkshopNir Kaufman
 
Interview Question & Answers for Selenium Freshers | LearningSlot
Interview Question & Answers for Selenium Freshers | LearningSlotInterview Question & Answers for Selenium Freshers | LearningSlot
Interview Question & Answers for Selenium Freshers | LearningSlotLearning Slot
 
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019Loiane Groner
 
Building a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring BootBuilding a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring BootOmri Spector
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practiceMikalai Alimenkou
 

What's hot (20)

Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring: Overview do framework mais popular para desenvolvimento em Java
Spring: Overview do framework mais popular para desenvolvimento em JavaSpring: Overview do framework mais popular para desenvolvimento em Java
Spring: Overview do framework mais popular para desenvolvimento em Java
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVC
 
Spring Framework - Validation
Spring Framework - ValidationSpring Framework - Validation
Spring Framework - Validation
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Angular 4 and TypeScript
Angular 4 and TypeScriptAngular 4 and TypeScript
Angular 4 and TypeScript
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
Unit 4
Unit 4Unit 4
Unit 4
 
Jdbc connectivity in java
Jdbc connectivity in javaJdbc connectivity in java
Jdbc connectivity in java
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applications
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++
 
Angular directives and pipes
Angular directives and pipesAngular directives and pipes
Angular directives and pipes
 
Servlets
ServletsServlets
Servlets
 
Angular Pipes Workshop
Angular Pipes WorkshopAngular Pipes Workshop
Angular Pipes Workshop
 
Interview Question & Answers for Selenium Freshers | LearningSlot
Interview Question & Answers for Selenium Freshers | LearningSlotInterview Question & Answers for Selenium Freshers | LearningSlot
Interview Question & Answers for Selenium Freshers | LearningSlot
 
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019
 
Building a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring BootBuilding a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring Boot
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practice
 

Similar to Shallow copy and deep copy

Web2py Code Lab
Web2py Code LabWeb2py Code Lab
Web2py Code LabColin Su
 
Functional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with PythonFunctional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with PythonCarlos V.
 
Palestra sobre Collections com Python
Palestra sobre Collections com PythonPalestra sobre Collections com Python
Palestra sobre Collections com Pythonpugpe
 
Ecto DSL Introduction - Yurii Bodarev
Ecto DSL Introduction - Yurii BodarevEcto DSL Introduction - Yurii Bodarev
Ecto DSL Introduction - Yurii BodarevElixir Club
 
Yurii Bodarev - Ecto DSL
Yurii Bodarev - Ecto DSLYurii Bodarev - Ecto DSL
Yurii Bodarev - Ecto DSLElixir Club
 
IBM Informix dynamic server 11 10 Cheetah Sql Features
IBM Informix dynamic server 11 10 Cheetah Sql FeaturesIBM Informix dynamic server 11 10 Cheetah Sql Features
IBM Informix dynamic server 11 10 Cheetah Sql FeaturesKeshav Murthy
 
Writing Readable Code with Pipes
Writing Readable Code with PipesWriting Readable Code with Pipes
Writing Readable Code with PipesRsquared Academy
 
Learning Git with Workflows
Learning Git with WorkflowsLearning Git with Workflows
Learning Git with WorkflowsMosky Liu
 
Module wise format oops questions
Module wise format oops questionsModule wise format oops questions
Module wise format oops questionsSANTOSH RATH
 
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲Mohammad Reza Kamalifard
 
Gsp 215 Exceptional Education / snaptutorial.com
Gsp 215  Exceptional Education / snaptutorial.comGsp 215  Exceptional Education / snaptutorial.com
Gsp 215 Exceptional Education / snaptutorial.comBaileya55
 
Special topics about stocks and bonds using algebra
Special topics about stocks and bonds using algebraSpecial topics about stocks and bonds using algebra
Special topics about stocks and bonds using algebraRomualdoDayrit1
 
Numbers obfuscation in Python
Numbers obfuscation in PythonNumbers obfuscation in Python
Numbers obfuscation in Pythondelimitry
 
Introduction to R - Lab slides for UGA course FANR 6750
Introduction to R - Lab slides for UGA course FANR 6750Introduction to R - Lab slides for UGA course FANR 6750
Introduction to R - Lab slides for UGA course FANR 6750richardchandler
 
Wellington APAC Groundbreakers tour - Upgrading to the 12c Optimizer
Wellington APAC Groundbreakers tour - Upgrading to the 12c OptimizerWellington APAC Groundbreakers tour - Upgrading to the 12c Optimizer
Wellington APAC Groundbreakers tour - Upgrading to the 12c OptimizerConnor McDonald
 
CS Sample Paper 1
CS Sample Paper 1CS Sample Paper 1
CS Sample Paper 1kvs
 

Similar to Shallow copy and deep copy (20)

Web2py Code Lab
Web2py Code LabWeb2py Code Lab
Web2py Code Lab
 
Functional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with PythonFunctional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with Python
 
Palestra sobre Collections com Python
Palestra sobre Collections com PythonPalestra sobre Collections com Python
Palestra sobre Collections com Python
 
Ecto DSL Introduction - Yurii Bodarev
Ecto DSL Introduction - Yurii BodarevEcto DSL Introduction - Yurii Bodarev
Ecto DSL Introduction - Yurii Bodarev
 
Yurii Bodarev - Ecto DSL
Yurii Bodarev - Ecto DSLYurii Bodarev - Ecto DSL
Yurii Bodarev - Ecto DSL
 
IBM Informix dynamic server 11 10 Cheetah Sql Features
IBM Informix dynamic server 11 10 Cheetah Sql FeaturesIBM Informix dynamic server 11 10 Cheetah Sql Features
IBM Informix dynamic server 11 10 Cheetah Sql Features
 
Writing Readable Code with Pipes
Writing Readable Code with PipesWriting Readable Code with Pipes
Writing Readable Code with Pipes
 
LalitBDA2015V3
LalitBDA2015V3LalitBDA2015V3
LalitBDA2015V3
 
Learning Git with Workflows
Learning Git with WorkflowsLearning Git with Workflows
Learning Git with Workflows
 
scripting in Python
scripting in Pythonscripting in Python
scripting in Python
 
Module wise format oops questions
Module wise format oops questionsModule wise format oops questions
Module wise format oops questions
 
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
 
Gsp 215 Exceptional Education / snaptutorial.com
Gsp 215  Exceptional Education / snaptutorial.comGsp 215  Exceptional Education / snaptutorial.com
Gsp 215 Exceptional Education / snaptutorial.com
 
Special topics about stocks and bonds using algebra
Special topics about stocks and bonds using algebraSpecial topics about stocks and bonds using algebra
Special topics about stocks and bonds using algebra
 
901131 examples
901131 examples901131 examples
901131 examples
 
Numbers obfuscation in Python
Numbers obfuscation in PythonNumbers obfuscation in Python
Numbers obfuscation in Python
 
Introduction to R - Lab slides for UGA course FANR 6750
Introduction to R - Lab slides for UGA course FANR 6750Introduction to R - Lab slides for UGA course FANR 6750
Introduction to R - Lab slides for UGA course FANR 6750
 
STACK Applications in DS
STACK Applications in DSSTACK Applications in DS
STACK Applications in DS
 
Wellington APAC Groundbreakers tour - Upgrading to the 12c Optimizer
Wellington APAC Groundbreakers tour - Upgrading to the 12c OptimizerWellington APAC Groundbreakers tour - Upgrading to the 12c Optimizer
Wellington APAC Groundbreakers tour - Upgrading to the 12c Optimizer
 
CS Sample Paper 1
CS Sample Paper 1CS Sample Paper 1
CS Sample Paper 1
 

More from Janu Jahnavi

Analytics using r programming
Analytics using r programmingAnalytics using r programming
Analytics using r programmingJanu Jahnavi
 
Google cloud platform
Google cloud platformGoogle cloud platform
Google cloud platformJanu Jahnavi
 
Google cloud Platform
Google cloud PlatformGoogle cloud Platform
Google cloud PlatformJanu Jahnavi
 
Apache spark with java 8
Apache spark with java 8Apache spark with java 8
Apache spark with java 8Janu Jahnavi
 
Apache spark with java 8
Apache spark with java 8Apache spark with java 8
Apache spark with java 8Janu Jahnavi
 
Categorizing and pos tagging with nltk python
Categorizing and pos tagging with nltk pythonCategorizing and pos tagging with nltk python
Categorizing and pos tagging with nltk pythonJanu Jahnavi
 
Categorizing and pos tagging with nltk python
Categorizing and pos tagging with nltk pythonCategorizing and pos tagging with nltk python
Categorizing and pos tagging with nltk pythonJanu Jahnavi
 

More from Janu Jahnavi (20)

Analytics using r programming
Analytics using r programmingAnalytics using r programming
Analytics using r programming
 
Software testing
Software testingSoftware testing
Software testing
 
Software testing
Software testingSoftware testing
Software testing
 
Spring
SpringSpring
Spring
 
Stack skills
Stack skillsStack skills
Stack skills
 
Ui devopler
Ui devoplerUi devopler
Ui devopler
 
Apache flink
Apache flinkApache flink
Apache flink
 
Apache flink
Apache flinkApache flink
Apache flink
 
Angular js
Angular jsAngular js
Angular js
 
Mysql python
Mysql pythonMysql python
Mysql python
 
Mysql python
Mysql pythonMysql python
Mysql python
 
Ruby with cucmber
Ruby with cucmberRuby with cucmber
Ruby with cucmber
 
Apache kafka
Apache kafkaApache kafka
Apache kafka
 
Apache kafka
Apache kafkaApache kafka
Apache kafka
 
Google cloud platform
Google cloud platformGoogle cloud platform
Google cloud platform
 
Google cloud Platform
Google cloud PlatformGoogle cloud Platform
Google cloud Platform
 
Apache spark with java 8
Apache spark with java 8Apache spark with java 8
Apache spark with java 8
 
Apache spark with java 8
Apache spark with java 8Apache spark with java 8
Apache spark with java 8
 
Categorizing and pos tagging with nltk python
Categorizing and pos tagging with nltk pythonCategorizing and pos tagging with nltk python
Categorizing and pos tagging with nltk python
 
Categorizing and pos tagging with nltk python
Categorizing and pos tagging with nltk pythonCategorizing and pos tagging with nltk python
Categorizing and pos tagging with nltk python
 

Recently uploaded

Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 

Recently uploaded (20)

Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 

Shallow copy and deep copy

  • 1. Shallow Copy and Deep Copy
  • 2. CHAPTER – 4 THE BASICS OF SEARCH ENGINE FRIENDLY DESIGN & DEVELOPMENT
  • 3. Copyright @ 2019 Learntek. All Rights Reserved. 3 Shallow Copy and Deep Copy In Python programming, many times we need to make a copy of variable(s). In orders to make copy different methods are available in the Python programming. Let’s take the example of the integer. >>> a = 10 >>> b = 10 >>> id(a) 140730625348928 >>> id(b) 140730625348928 >>> >>> x = 257 >>> y = 257 >>> id(x) 2067355160528 >>> id(y) 2067355160432 >>>
  • 4. Copyright @ 2019 Learntek. All Rights Reserved. 4 If an integer value is less than 256 then interpreter doesn’t make the copy, for a = 10 and b= 10 both the variables are referring to same memory allocation. But if the value exceeds the 256 then interpreter make a separate copy for each variable. See the figure below for more clarification
  • 5. Copyright @ 2019 Learntek. All Rights Reserved. 5 Let us take the example of Python list. See the following example >>> list1 = [1,2,3] >>> list2 = [1,2,3] >>> id(list1) 2067355168648 >>> id(list2) 2067353438600 >>>
  • 6. Copyright @ 2019 Learntek. All Rights Reserved. 6 Addresses of both the lists are different. Let us create the copy of one variable >>> list1 = [1,2,3] >>> list3 = list1 >>> >>> id(list1) 2067355168648 >>> id(list3) 2067355168648
  • 7. Copyright @ 2019 Learntek. All Rights Reserved. 7 It means both the variable are referring to same object or list. Let see the different methods to create the copy of variable which refers to a list.
  • 8. Copyright @ 2019 Learntek. All Rights Reserved. 8 First method >>> list4 = list1[:] >>> list4 [1, 2, 3] >>> id(list4) 2067355181192 >>> id(list1) 2067355168648 >>>
  • 9. Copyright @ 2019 Learntek. All Rights Reserved. 9 Second method >>> >>> list5 = list(list1) >>> >>> id(list5) 2067355181640 >>> >>> id(list1) 2067355168648 >>> You can check the addresses of list1 and list4, list1 and list5 are different.
  • 10. Copyright @ 2019 Learntek. All Rights Reserved. 10 Let us see one more example. >>> list1 = [1,2,["a","b"]] >>> >>> list2 = list1[:] >>> list2 [1, 2, ['a', 'b’]] >>> id(list2) 2067355167944 >>> id(list1) 2067355168136 >>>
  • 11. Copyright @ 2019 Learntek. All Rights Reserved. 11 Up to this level, nothing is surprising. Both the Python copy lists depicting different Python lists. >>> list1[2] ['a', 'b’] >>> id(list1[2]) 2067323314824 >>> >>> id(list2[2]) 2067323314824 >>> >>> list2[2] ['a', 'b’] >>>
  • 12. Copyright @ 2019 Learntek. All Rights Reserved. 12 The above code is very surprising. It means list1 and list2 contain the same sub-list.
  • 13. Copyright @ 2019 Learntek. All Rights Reserved. 13 This type of copy is called shallow copy. The inner sub-list address is same for the list1 and list2. Let us append the inner sub-list. >>> list1 = [1,2,["a","b"]] >>> list2 = list1 >>> >>> list2 = list1[:] >>> list2 [1, 2, ['a', 'b’]] [ >>> list1
  • 14. Copyright @ 2019 Learntek. All Rights Reserved. 14 [1, 2, ['a', 'b’]] >>> >>> list1[2].append('c’) >>> list1 [1, 2, ['a', 'b', 'c’]] >>> list2 [1, 2, ['a', 'b', 'c’]] >>> You can see if the sub-list list1[2] is updated then the impact also reflected to the list2[2].
  • 15. Copyright @ 2019 Learntek. All Rights Reserved. 15 Learn Python + Advanced Python Training If you use syntax list2 = list(list1) then this syntax would give you the same answer.
  • 16. Copyright @ 2019 Learntek. All Rights Reserved. 16 Deep Copy Now, what is the solution of shallow copy problem? The solution is a deep copy which allows a complete copy of the list. In other words, It means first constructing a new collection object and then recursively populating it with copies of the child objects found in the original. Fortunately, in Python, we have copy module to accomplish the task. See the following series of commands
  • 17. Copyright @ 2019 Learntek. All Rights Reserved. 17 >>> list1 = [1,2,["a","b"]] >>> from copy import deepcopy >>> list2 = deepcopy(list1) >>> id(list1) 1724712551368 >>> id(list2) 1724744113928 >>> >>> id(list1[2]) 1724712051336 >>> id(list2[2]) 1724713319304
  • 18. Copyright @ 2019 Learntek. All Rights Reserved. 18 You can see in both the Python list, list1 and list2, the sub-list is at different addresses. >>> list2[2] ['a', 'b’] >>> list2[2].append("c") >>> list2 [1, 2, ['a', 'b', 'c’]] >>> >>> list1 [1, 2, ['a', 'b’]] >>> If we append something in the sub-list of list2 then it does not reflect on the sub-list of list1. Let us take a complex example
  • 19. Copyright @ 2019 Learntek. All Rights Reserved. 19 >>> list1 = [1,2,("a","b",[1,2],3),4] >>> list1 [1, 2, ('a', 'b', [1, 2], 3), 4] >>> import copy >>> list2 = copy.deepcopy(list1) >>> list2 [1, 2, ('a', 'b', [1, 2], 3), 4] >>> list1[2][2] [1, 2] >>> list1[2][2].append(5) >>> list1 [1, 2, ('a', 'b', [1, 2, 5], 3), 4] >>> list2 [1, 2, ('a', 'b', [1, 2], 3), 4] >>>
  • 20. Copyright @ 2019 Learntek. All Rights Reserved. 20 We can say the deep copy is working fine. Let us take the case of Dictionary. In the dictionary, with the help of method copy, we can produce a copy of the dictionary. Let us see an example. >>> dict1 = {1: 'a', 2: 'b', 3: ['C', 'D’]} >>> >>> dict2 = dict1.copy() >>> >>> dict2[3] ['C', 'D’] >>> >>> dict2 {1: 'a', 2: 'b', 3: ['C', 'D’]} >>>
  • 21. Copyright @ 2019 Learntek. All Rights Reserved. 21 >>> dict2[3].append("E") >>> dict2 {1: 'a', 2: 'b', 3: ['C', 'D', 'E’]} >>> dict1 {1: 'a', 2: 'b', 3: ['C', 'D', 'E’]} >>> > >> id(dict1[3]) 1724744113864 >>> >>> id(dict2[3]) 1724744113864 >>>
  • 22. Copyright @ 2019 Learntek. All Rights Reserved. 22 So, what above series of command infers. See the following diagram.
  • 23. Copyright @ 2019 Learntek. All Rights Reserved. 23 It means the dict method copy also produce the shallow copy. Let take the help of deep copy to produce to a deep copy. >>> dict3 = deepcopy(dict1) >>> dict3 {1: 'a', 2: 'b', 3: ['C', 'D', 'E’]} >>> dict1[3].append("L") >>> >>> dict1 {1: 'a', 2: 'b', 3: ['C', 'D', 'E', 'L’]} >>> >>> dict3 {1: 'a', 2: 'b', 3: ['C', 'D', 'E’]} >>>
  • 24. Copyright @ 2019 Learntek. All Rights Reserved. 24 Means changes of dict1 are not reflecting dict3. In the end we can conclude that Making a shallow copy of an object won’t clone internal objects. Therefore, the copy is not fully independent of the original. A deep copy of an object will recursively clone internal objects. The clone is fully independent of the original, but creating a python deep copy is slower.
  • 25. Copyright @ 2019 Learntek. All Rights Reserved. 25 For more Training Information , Contact Us Email : info@learntek.org USA : +1734 418 2465 INDIA : +40 4018 1306 +7799713624