473,241 Members | 1,616 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,241 software developers and data experts.

is dict.copy() a deep copy or a shallow copy

Entering the following in the Python shell yields
help(dict.copy) Help on method_descriptor:

copy(...)
D.copy() -> a shallow copy of D

Ok, I thought a dictionary copy is a shallow copy. Not knowing exactly
what that meant I went to http://en.wikipedia.org/wiki/Deep_copy where
I could read

"...a deep copy is copy that contains the complete encapsulated data of
the original object, allowing it to be used independently of the
original object. In contrast, a shallow copy is a copy that may be
associated to data shared by the original and the copy"

Going back to Python shell I tested the following
D={'Python': 'good', 'Basic': 'simple'}
E=D.copy()
E {'Python': 'good', 'Basic': 'simple'} D['Basic']='oh my'
D {'Python': 'good', 'Basic': 'oh my'} E {'Python': 'good', 'Basic': 'simple'}
Hmm, this looks like a deep copy to me?? I also tried
D={'Python': 'good', 'Basic': 'simple'}
E=D
E {'Python': 'good', 'Basic': 'simple'} E['Basic']='oh my'
E {'Python': 'good', 'Basic': 'oh my'} D {'Python': 'good', 'Basic': 'oh my'}


which looks like a shallow copy to me?? So my hypothesis is that E=D is
a shallow copy while E=D.copy() is a deep copy.

So is the documentation wrong when they claim that D.copy() returns a
shallow copy of D, or did I misunderstand the difference between a deep
and shallow copy?

Thanks

Sep 4 '05 #1
2 12314
"Alex" <li*******@yahoo.se> wrote in
news:11**********************@z14g2000cwz.googlegr oups.com:
D={'Python': 'good', 'Basic': 'simple'}
E=D.copy()
E {'Python': 'good', 'Basic': 'simple'} D['Basic']='oh my'
D {'Python': 'good', 'Basic': 'oh my'} E {'Python': 'good', 'Basic': 'simple'}
Hmm, this looks like a deep copy to me?? I also tried

It is shallow, but strings are immutable so the difference is fairly
moot.
D={'Python': 'good', 'Basic': 'simple'}
E=D
E {'Python': 'good', 'Basic': 'simple'} E['Basic']='oh my'
E {'Python': 'good', 'Basic': 'oh my'} D {'Python': 'good', 'Basic': 'oh my'}


Here, E and D are different names for the same object. There is no
copy.
which looks like a shallow copy to me?? So my hypothesis is that
E=D is a shallow copy while E=D.copy() is a deep copy.
So is the documentation wrong when they claim that D.copy()
returns a shallow copy of D, or did I misunderstand the
difference between a deep and shallow copy?


Sort of, some examples:

Here d1 and d2 are copies. They can be independently changed to
refer to different objects:
d1={'a':1,'b':2}
d2=d1.copy()
d1['a']=3
d2['b']=4
d1 {'a': 3, 'b': 2} d2 {'a': 1, 'b': 4}

Again, d3 and d4 are copies, but instead of changing the objects
they refer to, we change the contents of the objects they refer to:
d3={'c':[3],'d':[4]}
d4=d3.copy()
d3['c'][0]=5
d4['d'][0]=6
d3 {'c': [5], 'd': [6]} d4

{'c': [5], 'd': [6]}

Both cases are shallow copies. In a deep copy, altering the contents
of d3['c'] would have no impact on the contents of d4['c'].

max
Sep 4 '05 #2
Thanks max,
Now it's much clearer. I made the following experiment
#1
D={'a':1, 'b':2}
D {'a': 1, 'b': 2} E=D.copy()
E {'a': 1, 'b': 2} D['a']=3
D {'a': 3, 'b': 2} E {'a': 1, 'b': 2}#2
D={'a':[1,3], 'b':[2,4]}
D {'a': [1, 3], 'b': [2, 4]} E=D.copy()
E {'a': [1, 3], 'b': [2, 4]} D['a'][0]=9
D {'a': [9, 3], 'b': [2, 4]} E {'a': [9, 3], 'b': [2, 4]}#3
import copy
F=copy.deepcopy(D)
D {'a': [9, 3], 'b': [2, 4]} F {'a': [9, 3], 'b': [2, 4]} D['a'][0]=7
D {'a': [7, 3], 'b': [2, 4]} F {'a': [9, 3], 'b': [2, 4]}


A shallow copy of an object is a copy of the first-level data members
and if one of the members is a pointer, then only the pointer value is
copied, not the structure pointed to by the pointer. The original
object and its shallow copy share the memory space occupied by these
structures.
A deep copy of an object is a copy of everything (including the
structures pointe to by the pointers). The original object and its deep
copy do not share any memory space.

In #1 no pointers are involved so changing a value affects only D but
not E.

In #2 D['a'] and E['a'] are pointers that both point to the same memory
space. Changing that memory space doesn't change the pointers
themsleves.

In #3 a deepcopy makes sure that a copy is made not just of the
pointers but also of the things pointed to.

So the lesson to be learned is that if you make a copy of a dictionary
whose values are pointers to other structures then a deepcopy prevents
a coupling between a the original and the copy.

Alex

Sep 5 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

42
by: Edward Diener | last post by:
Coming from the C++ world I can not understand the reason why copy constructors are not used in the .NET framework. A copy constructor creates an object from a copy of another object of the same...
5
by: Tony Johansson | last post by:
Hello! I'm reading in a book about C++ and that is something that sound strange. It says "Pointers have reference-assignment semantics similar to those in Java. For example, after the...
16
by: bluekite2000 | last post by:
I want Matrix A(B) to create shallow copy of B but A=B to create deep copy of B. Is that bad design? Why and why not?
4
by: fperfect13 | last post by:
Hi, I wanted to perform a deep copy of an array. Searching on google I ran into different opinions : C# Interview Questions (http://blogs.wwwcoder.com/tsvmadhav/archive/2005/04/08/2882.aspx)...
26
by: saxenavaibhav17 | last post by:
what is Deep Copy, Shallow copy and Bitwise copy, Memberwise copy? and what is the difference between them? pls help vaibhav
11
by: dalu.gelu | last post by:
Hi, can anyone help me by writing a sample code of defining a copy constructor in a class having data member as an object of another class. for eg: class A{ int x; public: A(){ x=6;} };
13
by: blangela | last post by:
I have decided (see earlier post) to paste my Word doc here so that it will be simpler for people to provide feedback (by directly inserting their comments in the post). I will post it in 3 parts...
4
by: shuisheng | last post by:
Dear All, Is there any easy way to make sure all my object copies are deep copy or shallow copy? I do not like to implement it in each class one by one. Thanks, Shuisheng
9
by: hfinster | last post by:
Hello, could somebody please shed light on the following problem with g++ (4.03 and 3.3.6 as well)? Obviously, the copy constructor is not executed, if I assign the result of a function call to...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.