Understanding dict.copy() - shallow or deep?
By "shallow copying" it means the content of the dictionary is not copied by value, but just creating a new reference.
>>> a = {1: [1,2,3]}
>>> b = a.copy()
>>> a, b
({1: [1, 2, 3]}, {1: [1, 2, 3]})
>>> a[1].append(4)
>>> a, b
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
In contrast, a deep copy will copy all contents by value.
>>> import copy
>>> c = copy.deepcopy(a)
>>> a, c
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
>>> a[1].append(5)
>>> a, c
({1: [1, 2, 3, 4, 5]}, {1: [1, 2, 3, 4]})
So:
b = a
: Reference assignment, Makea
andb
points to the same object.b = a.copy()
: Shallow copying,a
andb
will become two isolated objects, but their contents still share the same referenceb = copy.deepcopy(a)
: Deep copying,a
andb
's structure and content become completely isolated.
What is the difference between a deep copy and a shallow copy?
Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.
Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.
Why would the element of the original dictionary changes when I change the one of the copy dictionary?
This is the difference between a "shallow" copy and a "deep copy".
In a shallow copy, the object fields are copied over as references. If you change one, the other also changes since the reference is to the same memory address. In a deep copy, actual new copies of objects get created in entirely new addresses.
Instead of using .copy()
, you should use copy.deepcopy()
.
What is the difference between shallow copy, deepcopy and normal assignment operation?
Normal assignment operations will simply point the new variable towards the existing object. The docs explain the difference between shallow and deep copies:
The difference between shallow and deep copying is only relevant for
compound objects (objects that contain other objects, like lists or
class instances):
A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the
original.
Here's a little demonstration:
import copy
a = [1, 2, 3]
b = [4, 5, 6]
c = [a, b]
Using normal assignment operatings to copy:
d = c
print id(c) == id(d) # True - d is the same object as c
print id(c[0]) == id(d[0]) # True - d[0] is the same object as c[0]
Using a shallow copy:
d = copy.copy(c)
print id(c) == id(d) # False - d is now a new object
print id(c[0]) == id(d[0]) # True - d[0] is the same object as c[0]
Using a deep copy:
d = copy.deepcopy(c)
print id(c) == id(d) # False - d is now a new object
print id(c[0]) == id(d[0]) # False - d[0] is now a new object
When a key has a list value, using deep copy and shallow copy will have some differences
From the docs:
The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):
1.A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in
the original.2.A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
so..
- yes
- yes
- No
When you use shallow copy,for string and tuple it does not create a new object.
ex :
>>> s1 = "string1"
>>> s2 = copy.copy(s1)
>>> id(s2) == id(s1)
True
>>> id(s2[0]) == id(s1[0])
True
both are pointing to same object..!
- Yes,if we use deep copy,new objects are created for dictionaries and lists as they are compound objects.
check this link for more info:
What exactly is the difference between shallow copy, deepcopy and normal assignment operation?
Related Topics
Use Df Command to Show Only the %Used
Magicexception:File 5.41 Supports Only Version 16 Magic File, Magic.Mgc Is Version 14
Tutorial or Guide for Scripting Xcode Build Phases
How to Upload File with Python Requests
How to Set Python's Default Version to 3.X on Os X
How to Rename a File Using Python
Formatting Floats Without Trailing Zeros
Typeerror: 'Module' Object Is Not Callable
Else Clause on Python While Statement
Find the Column Name Which Has the Maximum Value for Each Row
What Is the Correct Way to Include Localisation in Python Packages
Module Not Found After Building Python Project by Using Pysinstaller
Can't Start Foreman in Heroku Tutorial Using Python
Custom Sorting in Pandas Dataframe
Creating a JSON Response Using Django and Python
How Does Zip(*[Iter(S)]*N) Work in Python