Last active
December 28, 2015 08:19
-
-
Save yangshun/7470943 to your computer and use it in GitHub Desktop.
Demonstrating the differences between deep and shallow copy in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# no copy | |
a = {1:'a', 2:'b', 3:{4:'c', 5:'d'}} | |
b = a | |
b[1] = 'lol' | |
print(a[1]) | |
b[3][4] = 'haha' | |
print(a[3][4]) | |
# shallow copy | |
c = {1:'a', 2:'b', 3:{4:'c', 5:'d'}} | |
d = c.copy() | |
d[1] = 'lol' | |
print(c[1]) | |
d[3][4] = 'haha' | |
print(c[3][4]) | |
# we define our own deepcopy function | |
def deepcopy(d): | |
e = d.copy() | |
for item in e.keys(): | |
if type(e[item]) == dict: | |
e[item] = deepcopy(e[item]) | |
return e | |
# deep copy | |
e = {1:'a', 2:'b', 3:{4:'c', 5:'d'}} | |
f = deepcopy(e) | |
f[1] = 'lol' | |
print(e[1]) | |
f[3][4] = 'haha' | |
print(e[3][4]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment