473,763 Members | 7,727 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

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

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 12350
"Alex" <li*******@yaho o.se> wrote in
news:11******** **************@ z14g2000cwz.goo glegroups.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
5804
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 kind. It sounds simple but evidently .NET has difficulty with this concept for some reason. I do understand that .NET objects are created on the GC heap but that doesn't mean that they couldn't be copied from another object of the same kind when...
5
3288
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 assignment Student* john = michael; both john and michael share the same object. This type of an assignment is different then value-assignmnet semantics used by class variables, as in
16
3141
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
52308
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) 10.What's the difference between the System.Array.CopyTo() and System.Array.Clone()?
26
15805
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
1962
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
5020
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 to make it more manageable. Below is a draft of a document that I plan to give to my introductory C++ class. Please note that I have purposely left out any mention of safety issues in the ctors which could be resolved thru some combination...
4
3148
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
2242
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 a (new) variable. Instead the memory location (address) of a temporary result variable from the function is used. This is my test code:
0
9563
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
9937
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9822
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8821
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7366
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5270
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3917
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3522
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.